Adding persistence to your app using JPA (Java Persistence API)
You will learn
In this tutorial you will implement a simple domain model and implement the corresponding persistence layer using JPA (Java Persistence API). The domain model only features a single class: FavoriteCity, so that we can bookmark or favorite our favorite cities.
Step 1: Create a base class
Let’s create a base class for our domain model first. That’s usually considered best practices as it provides us with a central place to add common functionality to be shared across all domain model objects on later. For that purpose, select New > Class from the context menu entry on the weatherapp project and provide the following details:
Next, we need to create a configuration file for our persistence layer. By Maven conventions, these non-source code artifacts should be located in a separate source code folder called: src/main/resources. Hence, let’s create that source folder via the corresponding context menu entry on the Java Resources node in the Project Explorer: New > Source Folder. Provide the following information:
Next, we need to add some more dependencies to our pom.xml file. In this case, the most important dependency is on EclipseLink (our JPA implementation of choice). However, we also need to declare dependencies for the Derby DB and Jackson (a serialization framework needed to convert data into JSON and vice versa.)
To register our RESTful service implementation in the web.xml configuration file, add the fully qualified classname of our FavoriteCityService class to the comma-separated list of jaxrs.serviceClasses. See the snippet below for where to enter the fully qualified classname inside the <param-value> element (don’t forget the comma at the end of the AuthenticationService line).
The last change to make is to define a DataSource within the web.xml in order to connect to the underlying database. To do this, copy and paste the following XML snippet after the closing </welcome-file-list> tag:
Once you execute the call, you’ll see two empty brackets “” (indicating an empty array) after successful authentication. Don’t worry, we haven’t saved any cities as favorites yet, so that’s just what we would expect.