Jersey Spring Hibernate Example

Jersey spring hibernate example tutorial will drive you on Exposing JPA entity as REST resource. Let’s have look into this Jersey spring tutorial explained spring integration with jersey. We will use the same code base and will create new entity User.

Installations:

  • Eclipse Mars
  • Java 8
  • Spring 4.3.5.RELEASE
  • Hibernate  4.3.6.Final
  • Maven 4
  • MySQL 5.1.31

REST JPA Entity Example:

In this tutorial, we will integrate with spring and JPA. We use Hibernate as JPA provider. REST JPA entities Tutorial

  • Create Maven Project:  Open eclipse and click on File -> New -> Maven Project. In which select “create simple project” and provide below details:REST Spring JPA example
  • Let’s create project structure:
    • org.javasavvy.rest.controller  ->  REST Resources classes
    • {base-package}.rest.modal    ->  JSON/XML POJO’s
    • DAO                                   ->   Data Access Layer classes
    • Services                             ->   Service Layer Classes
    • Entities                               ->  JPA Entities
    • src/main/resources/META-INF/persistence.xml file
    • src/main/resources/applicationContext*   – spring configration
    • Project structure  is :Jersey-JPA-spring
  • As explained in the Jersey  Spring tutorial, configure the  REST Servlet configuration and spring configurations in web.xml like below:
    1. <context-param>
            <param-name>log4jConfigLocation</param-name>
            <param-value>/WEB-INF/log4j.properties</param-value>
       </context-param>
       <listener>
            <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
       </listener>
       <listener>
             <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
       </listener>
       <context-param>
            <param-name>contextConfigLocation</param-name>
           <param-value>
                classpath:applicationContext.xml
                classpath*:applicationContext-jdbc.xml
           </param-value>
       </context-param>
       <servlet>
            <servlet-name>jersey-spring</servlet-name>
            <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
            <init-param>
               <param-name>com.sun.jersey.config.property.packages</param-name>
               <param-value>org.javasavvy.rest</param-value>
           </init-param>
          <init-param>
             <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
             <param-value>true</param-value>
          </init-param>
         <load-on-startup>1</load-on-startup>
       </servlet>
       <servlet-mapping>
            <servlet-name>jersey-spring</servlet-name>
            <url-pattern>/rest/*</url-pattern>
       </servlet-mapping>

JPA Configuration in spring context:

In applicationContext-jdbc.xml file, configure the datasource, entity manager for JPA (SessionFactory in case hibernate) and Transaction manger. 

  • We will configure JPA Transaction Manager that requires JPA Entity Manager Factory and tx:annotation-driven enables declarative transaction on classes with @Transactional annotation.
    •  <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
             <property name="entityManagerFactory" ref="entityManagerFactory" />
       </bean>
  • Configure Entity Manager factory and provide Datasource and Persistent Unit names:
    • <bean id="entityManagerFactory"  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="persistenceUnitName" value="JPA-Tutorial" />
            <property name="jpaVendorAdapter">
              <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
            </property>
           <property name="jpaProperties">
               <props>
                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                 <prop key="hibernate.show_sql">true</prop>
                 <prop key="hibernate.format_sql">false</prop>
                 <prop key="hibernate.hbm2ddl.auto">update</prop>
               </props>
            </property>
       </bean>
  • Configure Datasource as spring:
    •  <bean id="dataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
             <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
             <property name="url" value="jdbc:mysql://localhost:3306/javasavvy" />
             <property name="username" value="root" />
             <property name="password" value="root" />
       </bean>
  • <context:component-scan base-package=”org.javasavvy.rest.controller” /> :  Scans packages for beans and creates beans in spring container
  • <context:annotation-config />:   Enables spring annotations marked on Classes: @Service, @Component,@Repository

applicationContext-jdbc.xml file looks like:

  • <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
     xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-4.0.xsd
     http://www.springframework.org/schema/tx
     http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
     <context:annotation-config />
     <context:component-scan base-package="org.javasavvy.rest.controller" />
     <context:component-scan base-package="org.javasavvy.tutorial.services" />
     <context:component-scan base-package="org.javasavvy.tutorial.dao" />
     <tx:annotation-driven transaction-manager="transactionManager" />
    
     <bean id="dataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
           <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
           <property name="url" value="jdbc:mysql://localhost:3306/javasavvy" />
           <property name="username" value="root" />
           <property name="password" value="root" />
     </bean>
     <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
           <property name="entityManagerFactory" ref="entityManagerFactory" />
     </bean>
     <bean id="entityManagerFactory"  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
          <property name="dataSource" ref="dataSource" />
          <property name="persistenceUnitName" value="JPA-Tutorial" />
          <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
          </property>
         <property name="jpaProperties">
             <props>
               <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
               <prop key="hibernate.show_sql">true</prop>
               <prop key="hibernate.format_sql">false</prop>
               <prop key="hibernate.hbm2ddl.auto">update</prop>
             </props>
          </property>
     </bean>
    
     <bean  class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
    
    </beans>

JPA Entities:

JPA uses ORM i.e Object Relation mapping with annotations such as @Table, @Entity,@Column on POJO to map with tables. Each Object represents a row in the table and JPA will take care of auto conversion of Table to POJO vice versa.

  •  JPA requires persistence.xml file that will create persistence unit with specified entities. Create persistent.xml file in resources/META-INF and map the JPA entities under persistence-unit
    1. <?xml version="1.0" encoding="UTF-8"?>
      <persistence version="2.0" 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">
       <persistence-unit name="JPA-Tutorial">
       <class>org.javasavvy.tutorial.entity.User</class>
       </persistence-unit>
      </persistence>
  • Create Entity User annotate with @Table and required fields.User JPA Entity
  • Service Impl Class :   Annotation @Service will create bean with name “userService” and inject the “userService” bean in other classes with below code:
    •  @Autowired(required=true)
       @Qualifier("userService")
       private UserService userService;

      Spring sample Service class

  • Data Access layer class is:  Use @Repository annotation instead of @Service and also annotate with  declarative transactions with @Transactional annotation.User DAO Class
  • REST Controller is :User Rest Controller
  • Now deploy to tomcat and create the user with url and you can get the success response:
    1. http://localhost:8080/jersey-spring-jpa/rest/user/create-user
    2. {
      "firstName": "jayaram",
      "lastName": "pokuri",
      "email": "[email protected]",
      "sex": "male",
      "password": "test",
      "userId": 0
      }

      Hope this helps

 

 

Click here to download code

5 thoughts on “jersey spring hibernate example”
    1. You can download the code at bottom of page and you can find pom.xml file in that

Comments are closed.