Friday, February 26, 2016

NetBeans Java EE Tip #3: RESTful Web Services from Database

Many modern web applications are moving towards the use of stateless communications using HTTP.  The REST (Representational State Transfer) architectural style is oftentimes utilized to design networked applications, and with Java EE 7 it is very easy to develop a RESTful backend for database communication.  Using a simple POJO (plain old Java object), one can provide a complete solution for stateless database communication by applying annotations to method signatures.

NetBeans allows developers to create RESTful solutions even more productively by providing tools such as the ability to generate RESTful Web Services from a database.  This allows a developer to select one or more database tables from which to generate RESTful web services without any coding at all.  Very similar to "Entity Classes from Database", this process takes it one step further and not only produces the required entity classes, but also a complete web service class for performing CRUD database operations in a RESTful manner.

To get started, right-click on your source package within NetBeans and choose "New"->"Web Services"->"RESTful Web Services from Database" (Figure 1).  This will open the "New RESTful Web Services from Database" dialog.
Figure 1:  Creating RESTful Web Services from Database

Figure 2:  New RESTful Web Services from Database Dialog

In this dialog, select the data source to which you would like to connect, and then choose one or more tables from the "Available Tables" list, and add to the list of "Selected Tables".  Choose "Next".  On the next dialog, you will have the ability to specify a package location, as well as which annotations to generate for your entity classes (Figure 3).

Figure 3:  Specify options for your entity classes

Next, you have the ability to specify the package location for your service classes.  The NetBeans wizard will also produce an ApplicationConfig class if one has not already been produced for your project, and place it into this resource package.  The ApplicationConfig is required to configure an access point for the RESTful web services in your application.

Figure 4:  Specify Resource Package Location

That's "Finish" to generate the classes.  You will see that entity classes are generated for all of the database tables (and optionally those tables that are related).  In the elected resource package, web service classes are generated for each of the entity classes, and the ApplicationConfig class is also produced if it did not exist already (Figure 5).

Figure 5:  Classes Generated by Wizard

After following these procedures, you now have a completely usable web service for each of the database tables that you had selected.  These web service classes can be utilized to develop stateless applications that will communicate with your database.

Figure 6:  RESTful Web Service Class

No comments:

Post a Comment

Please leave a comment...