Configuring JPA in Jersey 2 Web App

With this blog post, I am going to share what I needed to do to make JPA work in my Jersey 2 Web Services App.

I have created my Jersey 2 app using the following maven snippet:

mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes \
    -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeVersion=2.26

I then opened pom.xml and added a few new dependencies which I will list below.

POM.XML Dependencies

Open pom.xml file and add the following dependencies:

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
       <dependency>
           <groupId>org.hibernate</groupId>
           <artifactId>hibernate-entitymanager</artifactId>
           <version>4.2.5.Final</version>
       </dependency>
       <dependency>
           <groupId>org.hibernate</groupId>
           <artifactId>hibernate-core</artifactId>
           <version>4.2.5.Final</version>
       </dependency>
       
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>5.1.41</version>
       </dependency>

My Jersey 2 apps persist data into MySQL, so this is why you see a dependency for MySQL. The complete pom.xml file of my project is below:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.appsdeveloperblog.app.ws</groupId>
    <artifactId>mobile-app-ws</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>mobile-app-ws</name>

    <build>
        <finalName>mobile-app-ws</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
            <!-- artifactId>jersey-container-servlet</artifactId -->
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-binding</artifactId>
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.2.5.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.2.5.Final</version>
        </dependency>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
 

    </dependencies>
    <properties>
        <jersey.version>2.26</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

Persistence.xml File

Next, for my JPA to work in Jersey 2 container-deployable web app, I needed to create and add to my project a new file called persistence.xml. Please note that I have replaced the database username, password and the database name with a text you need to replace with actual values.

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
                  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
    <persistence-unit name="mysql_persistence_unit" transaction-type="RESOURCE_LOCAL">
     <description> Hibernate JPA Configuration Example</description>
    
        <class>com.appsdeveloperblog.com.app.ws.io.entities.UserEntity</class>

      <properties>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/database_name_here"/>
        <property name="javax.persistence.jdbc.user" value="database user name here "/> 
        <property name="javax.persistence.jdbc.password" value="database user password here"/>
        
        <property name="hibernate.id.new_generator_mappings" value="true"/> 
        <property name="show_sql" value="true"/>
        <property name="hibernate.hbm2ddl.auto" value="update"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> 
        </properties>
 
    </persistence-unit>
</persistence>

Persist Object in MySQL Database with JPA

And finally, to be able to persist Java objects in my Jersey 2 with JPA Web app I needed to create a new Data Access Object or a repository Java class that creates the entity manager using the value I have provided in my persistence.xml file above and then stores the UserEntity Java object in MySQL database.

public class UserRepositoryImpl implements UserRepository {

    @Override
    public void save(UserEntity userEntity) {
         
       EntityManager entityManager = Persistence.createEntityManagerFactory("mysql_persistence_unit").createEntityManager();
       EntityTransaction transaction = entityManager.getTransaction();  
       try {
         transaction.begin();
         entityManager.persist(userEntity);
         transaction.commit();
       } catch (Exception e) {
         e.printStackTrace();
         transaction.rollback();
         throw e; 
       } finally {
         entityManager.clear(); 
         entityManager.close();
       }     

    }
}

Hope this helps you. If you are learning Java Persistence and are actively looking for a good step by step learning materials, check the list of video courses below. One of them might help you out and even much more – Make you a confident developer who can easily build an API with RESTful Web Services using Jersey, Hibernate, and JPA.

Learning RESTful Web Services Development