Search code examples
java-8maven-3jersey-2.0spring-4hibernate-5.x

How can i setup a Project using Jersey, Spring, Hibernate and maven


How can I configure a Java project using below libraries?

  1. Jersey 2.25
  2. Spring 4.3.5 RELEASE
  3. Hibernate 5.5.6 Final
  4. Apache Maven
  5. Java 8

Solution

  • Project is based on JERSEY 2.25, SPRING 4.3.5 RELEASE, HIBERNATE 5.5.6 Final, USING MAVEN

    I thought of sharing my knowledge on creating basic setup, to give a kick start to your project. I am placing this request, because i couldn't find any complete solution for JERSEY-SPRING-HIBERNATE setup and configuration. As i went through a lot to problem to find the solution. You can also refer to my Github project Jersey-Spring-Hibernate-Project .


    To start a project open Eclipse IDE.

    File -> new -> other -> Maven -> Maven Project -> press Next -> press Next

    in the filter, look for jersey-quickstart-webapp with version 2.24 or later.

    if you don't find it, then click Add Archetype

    Archetype Group id : org.glassfish.jersey.archetypes

    Archetype Artifact id: jersey-quickstart-webapp

    Archetype Version: 2.24

    Repository URL: leave it empty

    Press OK.

    Now again follow steps from start and now you will find jersey-quickstart-webapp with version 2.24.

    select it and press NEXT.

    Provide your Group id: "which will be your package name", in my case it is org.pramod.

    provide your Artifact id: "This is your project name"

    Package: in this project is org.pramod

    click Finish


    To setup our project we need 4 files to configure.

    1. web.xml
    2. pom.xml
    3. applicationContext.xml
    4. MyApplication.java

    File name: src/main/webapp/WEB-INF/web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
    
      <!-- REGISTERING LISTNER -->
      <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
      </listener>
    
      <!--  TO REGISTER THE BEANS -->  
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
      </context-param>
    
      <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <!-- TO REGISTER THE SERVLET which is mentioned in the MyApplication -->
        <init-param>
          <param-name>javax.ws.rs.Application</param-name>
          <param-value>org.pramod.config.MyApplication</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
      </servlet-mapping>
    
    </web-app>
    

    File Name: src/main/resources/applicationContext.xml

    <?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:aop="http://www.springframework.org/schema/aop"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/jerseyspringhibernate"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </bean>
    
        <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                    <prop key="hibernate.hbm2ddl.auto">update</prop>
                    <prop key="hibernate.show_sql">true</prop>
                </props>
            </property>
            <property name="annotatedClasses">
                <list>
                    <value>org.pramod.model.Customer</value>
                </list>
            </property>
        </bean>
    
        <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
        <bean id="customerService" class="org.pramod.service.CustomerServiceImpl"/>
        <bean id="customerDao" class="org.pramod.dao.CustomerDaoImpl"/>
    
    </beans>
    

    File Name : pom.xml

    <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>org.pramod</groupId>
      <artifactId>JerseySpringHibernate</artifactId>
      <packaging>war</packaging>
      <version>0.0.1-SNAPSHOT</version>
      <name>JerseySpringHibernate</name>
    
      <build>
         <finalName>JerseySpringHibernate</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.8</source>
                    <target>1.8</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>
          </dependency>
    
          <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
          </dependency>
    
          <dependency>
            <groupId>org.glassfish.jersey.ext</groupId>
            <artifactId>jersey-spring3</artifactId>
          </dependency>
    <!--         
          <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
            <exclusions>
                <exclusion>
                    <artifactId>javax.servlet</artifactId>
                    <groupId>servlet-api</groupId>
                </exclusion>
            </exclusions>
          </dependency>
     -->       
    <!-- ******************************************************** -->       
          <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
          </dependency>
    
    <!-- ********************** SPRING 4.3.4 *****************************  -->
    
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
          </dependency>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
          </dependency>     
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
          </dependency>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                 </exclusion>
            </exclusions>
          </dependency>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
          </dependency>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
          </dependency>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring.version}</version>
          </dependency>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-instrument</artifactId>
            <version>${spring.version}</version>
          </dependency>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-instrument-tomcat</artifactId>
            <version>${spring.version}</version>
          </dependency>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
          </dependency>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${spring.version}</version>
          </dependency>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-messaging</artifactId>
              <version>${spring.version}</version>
          </dependency>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-orm</artifactId>
              <version>${spring.version}</version>
          </dependency>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-oxm</artifactId>
              <version>${spring.version}</version>
          </dependency>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-test</artifactId>
              <version>${spring.version}</version>
          </dependency>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-tx</artifactId>
              <version>${spring.version}</version>
          </dependency>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-web</artifactId>
              <version>${spring.version}</version>
          </dependency>
            <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-webmvc</artifactId>
              <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc-portlet</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-websocket</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
    <!-- ********************* HIBERNATE 5.5.6 ************************* -->  
    
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-search-orm</artifactId>
                <version>${hibernate.version}</version>
            </dependency>
    
    <!-- ********************* MY SQL CONNECTOR *************************  -->  
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.38</version>
            </dependency>
    
        </dependencies>
    
        <properties>    
            <jersey.version>2.25</jersey.version>
            <spring.version>4.3.5.RELEASE</spring.version>
            <hibernate.version>5.5.6.Final</hibernate.version>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>
    </project>
    

    Below mentioned Files are all java files, which are placed in the src/main/java/ followed by package name. Package name is org.pramod. Example src/main/java/org.pramod.*

    File Name : org.pramod.config.MyApplication.java

    package org.pramod.config;
    
    import org.glassfish.jersey.server.ResourceConfig;
    
    public class MyApplication extends ResourceConfig{
    
        public MyApplication(){
            register(MyResource.class);
            register(CustomerResource.class);
        }
    }
    

    THESE ARE THE SERVLET RESOURCE. 1. MyResource and 2. CustomerResource can be moved to org.pramod.resource package

    File Name : org.pramod.config.MyResource.java

    package org.pramod.config;
    
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    
    import org.pramod.service.CustomerService;
    import org.springframework.beans.factory.annotation.Autowired;
    
    /**
     * Root resource (exposed at "myresource" path)
     */
    @Path("myresource")
    public class MyResource {
    
        @Autowired
        CustomerService customerService;
    
    
        @GET
        @Produces(MediaType.TEXT_PLAIN)
        public String getIt() {
            return customerService.getStringTest();
        }
    }
    

    File Name: org.pramod.config.CustomerResource.java

    package org.pramod.config;
    
    import java.util.List;
    
    import javax.ws.rs.Consumes;
    import javax.ws.rs.DELETE;
    import javax.ws.rs.GET;
    import javax.ws.rs.POST;
    import javax.ws.rs.PUT;
    import javax.ws.rs.Path;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    
    import org.pramod.model.Customer;
    import org.pramod.service.CustomerService;
    import org.springframework.beans.factory.annotation.Autowired;
    
    @Path("customers")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public class CustomerResource {
    
      @Autowired
      CustomerService customerService;
    
      @GET
      public List<Customer> getCustomers(){
        return customerService.getAllCustomer();
      }
    
      @GET
      @Path("/{customerId}")
      public Customer getCustomer(@PathParam("customerId") int id){
        return customerService.getCustomerById(id);
      }
    
      @POST
      public Customer saveCustomer(Customer customer){
        return customerService.addCustomer(customer);
      }
    
      @PUT
      @Path("/{customerId}")
      public Customer updateCustomer(@PathParam("customerId") int id, Customer customer){
        return customerService.updateCustomer(id, customer);
      }
    
      @DELETE
      @Path("/{customerId}")
      public Customer removeCustomer(@PathParam ("customerId") int id ){
        return customerService.deleteCustomer(id);
      }
    }
    

    THESE ARE THE Spring Service Files and Interface. 1. CustomerService and 2. CustomerServiceImpl

    File Name: org.pramod.service.CustomerService.java

    package org.pramod.service;
    
    import java.util.List;
    
    import org.pramod.model.Customer;
    
    public interface CustomerService {
    
        String getStringTest();
        Customer addCustomer(Customer customer);
        Customer updateCustomer(int id, Customer customer);
        Customer deleteCustomer(int id);
        Customer getCustomerById(int id);
        List<Customer> getAllCustomer();
    }
    

    File Name: org.pramod.service.CustomerServiceImpl.java

    package org.pramod.service;
    
    import java.util.List;
    
    import org.pramod.dao.CustomerDao;
    import org.pramod.model.Customer;
    import org.springframework.beans.factory.annotation.Autowired;
    
    public class CustomerServiceImpl implements CustomerService {
    
      @Autowired
      private CustomerDao customerDao; 
    
      @Override
      public String getStringTest() {
        return customerDao.getStringTest();
      }
    
      @Override
      public Customer addCustomer(Customer customer) {
        return customerDao.addCustomer(customer);
      }
    
      @Override
      public Customer updateCustomer(int id, Customer customer) {
        return customerDao.updateCustomer(id, customer);
      }
    
      @Override
      public Customer deleteCustomer(int id) {
        return customerDao.deleteCustomer(id);
      }
    
      @Override
      public Customer getCustomerById(int id) {
        return customerDao.getCustomerById(id);
      }
    
      @Override
      public List<Customer> getAllCustomer() {
        return customerDao.getAllCustomer();
      }
    }
    

    These are the Hibernate Implementation Files and Interface.

    1. CustomerDao and 2. CustomerDaoImpl.

    If you dont want to implement HIBERNATE, than you can omit this two files and in the applicationContext.xml file DELETE the bean with id's "dataSource" and "sessionFactory". Remove the dependency of HIBERNATE in pom.xml


    File Name: org.pramod.dao.CustomerDao.java

    package org.pramod.dao;
    
    import java.util.List;
    
    import org.pramod.model.Customer;
    
    public interface CustomerDao {
    
        String getStringTest();
        Customer addCustomer(Customer customer);
        Customer updateCustomer(int id, Customer customer);
        Customer deleteCustomer(int id);
        Customer getCustomerById(int id);
        List<Customer> getAllCustomer();
    
    }
    

    File Name: org.pramod.dao.CustomerDaoImpl.java

    package org.pramod.dao;
    
    import java.util.List;
    
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.pramod.model.Customer;
    import org.springframework.beans.factory.annotation.Autowired;
    
    public class CustomerDaoImpl implements CustomerDao {
    
      @Autowired
      SessionFactory sessionFactory;
    
      @Override
      public String getStringTest(){
        String save = "Got it";
        return save;
      }
    
      @Override
      public Customer addCustomer(Customer customer) {      
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        try{
            session.save(customer);
            tx.commit();
            return customer;
        }catch(Exception e){
            tx.rollback();
            return null;
        }
      }
    
      @Override
      public Customer updateCustomer(int id, Customer cust) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        try{
            Customer customer = cust;
            customer.setId(id);
            session.update(customer);
            tx.commit();
            return customer;
        }catch(Exception e){
            tx.rollback();
            return null;
        }
      }
    
      @Override
      public Customer deleteCustomer(int id) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        try{
            Customer cust = session.get(Customer.class,id);
            session.delete(cust);
            tx.commit();
            return cust;
        }catch(Exception e){
            tx.rollback();
            return null;
        }
      }
    
      @Override
      public Customer getCustomerById(int id) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        try{
            Customer cust = session.get(Customer.class,id);
            tx.commit();
            session.close();
            return cust;
        }catch(Exception e){
            tx.rollback();
            session.close();
            return null;
        }       
      }
    
      @Override
      public List<Customer> getAllCustomer() {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        try{
            Query query = session.createQuery("from Customer");
            List<Customer> customers = query.list();
            tx.commit();
            session.close();
            return customers;
        }catch(Exception e){
            tx.rollback();
            session.close();
            return null;
        }       
      }
    
    }
    

    This is the Entity or Object of Customer type. If you don't want to you use Hibernate. Remove All the annotation

    File Name: org.pramod.model.Customer.java

    package org.pramod.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name="CUSTOMER")
    public class Customer {
    
      @Id @GeneratedValue
      @Column(name="customer_id")
      private int id;
      @Column
      private String firstName;
      @Column
      private String lastName;
      @Column
      private String street;
      @Column
      private String city;
      @Column
      private String state;
      @Column
      private int pin;
    
      public int getId() {
        return id;
      }
      public void setId(int id) {
        this.id = id;
      }
      public String getFirstName() {
        return firstName;
      }
      public void setFirstName(String firstName) {
        this.firstName = firstName;
      }
      public String getLastName() {
        return lastName;
      }
      public void setLastName(String lastName) {
        this.lastName = lastName;
      }
      public String getStreet() {
        return street;
      }
      public void setStreet(String street) {
        this.street = street;
      }
      public String getCity() {
        return city;
      }
      public void setCity(String city) {
        this.city = city;
      }
      public String getState() {
        return state;
      }
      public void setState(String state) {
        this.state = state;
      }
      public int getPin() {
        return pin;
      }
      public void setPin(int pin) {
        this.pin = pin;
      }
    }