Combining JPA and JAX-RS to Create RESTful Service
How to combine Java Persistence API (JPA) with JAX-RS to create a RESTful service.
Java Persistence API (JPA) abstracts the database interactions and treats them as objects rather than simply queries. Since these queries are now objects, the principles of Object-Oriented Programming (OOP) can come into play including, encapsulation, abstraction, inheritance, and polymorphism.
When creating a JPA application three things are required to build your foundation:
- Entity class - contains fields (variables) as well as getter and setter methods, annotated with @Entity
- persistence.xml - tells your program how to connect and interact with your database
- Resource class - where you implement your CRUD operations
One of the keys to persistence is the EntityManager which is associated with a persistence context. The EntityManager facilitates the interactions between your database and your program. Each method that talks to the database should get its own entity manager.
JPA has its own query language known as Java Persistence Query Language (JPQL), which can be used to when custom queries are needed. For simple CRUD operations however, you can generally rely on the built in functions persist (create), find (read), and remove (delete).
Since you’ve now gotten the JPA portion of your application set up you can now begin implementing the JAX-RS portion so you can use the data you retrieved in your app.
JAX-RS is a Java programming language API that provides support in creating web services in the REST architectural pattern. Several implementations exists including, Apache CXF, Jersey, RESTeasy, and WebSphere Application Server. Like JPA, JAX-RS uses annotations. Some of the most commonly used ones include @Path, @GET, @POST, @PUT, @DELETE, and @Produces/Consumes.