RestEasy: JAX-RS web service + Integrating with Spring MVC and Hibernate ORM framework

In this article, we will extend previous article to integrate with Hibernate ORM framework

JBoss RestEasy is a JAX-RS implementation for developing Restful web service in java. Once developed, it isn’t restricted to deploy only in JBoss Application Server but you can deploy in any other server like Apache Tomcat, Glassfish, Oracle Weblogic, etc

RestEasy official documentation for Spring+RestEasy integration see here

Annotation Used

  • @Path (ws.rs.Path)
  • @GET (ws.rs.GET)
  • @POST (ws.rs.POST)
  • @PUT (ws.rs.PUT)
  • @DELETE (ws.rs.DELETE)
  • @PathParam (ws.rs.PathParam)
  • @Consumes (ws.rs.Consumes)
  • @Produces (ws.rs.Produces)
  • @Controller(org.springframework.stereotype.Controller)
  • @Repository (org.springframework.stereotype.Repository)
  • MediaType (ws.rs.core.MediaType)

Technology Used

  • Java 1.7
  • Eclipse Luna IDE
  • RestEasy-3.0.8.Final
  • Spring-webmvc-3.2.11.RELEASE
  • Hibernate-4.2.15.Final
  • Apache Maven 3.2.1
  • Apache Tomcat 7.0.54
  • JBoss Application Server 7.1.1.Final
  • MySql-Connector-Java-5.1.32

Mavenize or download required jars

Add RestEasy-3.0.8.Final, Spring-3.2.11-Release, Hibernate-4.2.15.Final & MySql-Connector-Java-5.1.32 dependencies to pom.xml

	<properties>
		<resteasy.version>3.0.8.Final</resteasy.version>
		<resteasy.scope>compile</resteasy.scope> 		<!-- compile(Tomcat) / provided(JBoss) -->
		<spring.version>3.2.11.RELEASE</spring.version> <!-- 4.x doesn't work with RestEasy directly -->
		<hibernate.version>4.2.15.Final</hibernate.version>
		<mysql.version>5.1.32</mysql.version>
		<servlet.version>3.1.0</servlet.version>
		<jstl.version>1.2</jstl.version>
		<compileSource>1.7</compileSource>
		<maven.compiler.target>1.7</maven.compiler.target>
		<maven.compiler.source>1.7</maven.compiler.source>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<!-- RESTEasy JAX RS Implementation -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jaxrs</artifactId>
			<version>${resteasy.version}</version>
			<scope>${resteasy.scope}</scope>
		</dependency>

		<!-- Resteasy Servlet Container Initializer -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-servlet-initializer</artifactId>
			<version>${resteasy.version}</version>
			<scope>${resteasy.scope}</scope>
		</dependency>

		<!-- Resteasy JAXB Provider -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jaxb-provider</artifactId>
			<version>${resteasy.version}</version>
			<scope>${resteasy.scope}</scope>
		</dependency>

		<!-- Resteasy Jackson Provider -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jackson-provider</artifactId>
			<version>${resteasy.version}</version>
			<scope>${resteasy.scope}</scope>
		</dependency>

		<!-- RESTEasy JAX RS Client -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-client</artifactId>
			<version>${resteasy.version}</version>
			<scope>${resteasy.scope}</scope>
		</dependency>

		<!-- Resteasy Spring Integration -->
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-spring</artifactId>
			<version>${resteasy.version}</version>
		</dependency>

		<!-- Spring Framework-3.2.x -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Hibernate Core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-ehcache</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<!-- MySql-Connector -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.version}</version>
		</dependency>

		<!-- servlet-3.1.0 -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlet.version}</version>
		</dependency>

		<!-- JSTL for JSP pages -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>
	</dependencies>

Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the central repository or maven repository and download directly from Spring site include them in the classpath

JAXB – Generating java source files from XSD

Steps to generate java-sources from XML Schema Definition (XSD)

  • configure JAXB Maven plugin in pom.xml
  • write well-defined XSD for your service
  • use maven command “mvn generate-sources” to generate java source files

Configure JAXB Maven plugin

<!-- JAXB plugin to generate-sources from XSD -->
<plugin>
	<groupId>org.codehaus.mojo</groupId>
	<artifactId>jaxb2-maven-plugin</artifactId>
	<version>1.6</version>
	<executions>
		<execution>
			<goals>
				<goal>xjc</goal><!-- xjc/generate -->
			</goals>
			<configuration>
				<outputDirectory>${basedir}/generated/java/source</outputDirectory>
				<schemaDirectory>${basedir}/src/main/resources/com/resteasy/series/spring/mvc/hibernate/service/entities
				</schemaDirectory>
				<schemaFiles>*.xsd</schemaFiles>
				<schemaLanguage>XMLSCHEMA</schemaLanguage>
				<extension>true</extension>
				<args>
					<arg>-XtoString</arg>
				</args>
				<plugins>
					<plugin>
						<groupId>org.jvnet.jaxb2_commons</groupId>
						<artifactId>jaxb2-basics</artifactId>
						<version>0.6.4</version>
					</plugin>
				</plugins>
			</configuration>
		</execution>
	</executions>
</plugin>

Customer.xsd

Below XSD contains two elements with name “CustomerType” and “CustomerListType”

  • CustomerType contains three attributes namely customerId, name, age
  • CustomerListType which returns list of CustomerType
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	targetNamespace="http://benchresources.in/cdm/Customer" xmlns:tns="http://benchresources.in/cdm/Customer"
	elementFormDefault="qualified">

	<!-- player object with three attributes -->
	<xsd:element name="CustomerType">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element name="customerId" type="xsd:int" />
				<xsd:element name="name" type="xsd:string" />
				<xsd:element name="age" type="xsd:int" />
			</xsd:sequence>
		</xsd:complexType>
	</xsd:element>

	<!-- an object to contain lists of players referencing above player object -->
	<xsd:element name="CustomerListType">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element ref="tns:CustomerType" minOccurs="0"
					maxOccurs="unbounded" />
			</xsd:sequence>
		</xsd:complexType>
	</xsd:element>

</xsd:schema>

Run mvn generate-sources

Look at the generated java source files in the generated folder

CustomerType.java

package in.benchresources.cdm.customer;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "customerId",
    "name",
    "age"
})
@XmlRootElement(name = "CustomerType")
public class CustomerType {

    protected int customerId;
    @XmlElement(required = true)
    protected String name;
    protected int age;

    public int getCustomerId() {
        return customerId;
    }

    public void setCustomerId(int value) {
        this.customerId = value;
    }

    public String getName() {
        return name;
    }

    public void setName(String value) {
        this.name = value;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int value) {
        this.age = value;
    }
}

CustomerListType.java

package in.benchresources.cdm.customer;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "customerType"
})
@XmlRootElement(name = "CustomerListType")
public class CustomerListType {

    @XmlElement(name = "CustomerType")
    protected List<CustomerType> customerType;

    public List<CustomerType> getCustomerType() {
        if (customerType == null) {
            customerType = new ArrayList<CustomerType>();
        }
        return this.customerType;
    }
}

Directory Structure

Before moving on, let us understand the directory/package structure once you create project in Eclipse IDE

Maven has to follow certain directory structure

  • src/test/java –> test related files, mostly JUnit test cases
  • src/main/java –> create java source files under this folder
  • src/main/resources –> all configuration files placed here
  • src/test/resources –> all test related configuration files placed here
  • Maven Dependencies or Referenced Libraries –> includes jars in the classpath
  • WEB-INF under webapp –> stores web.xml & other configuration files related to web application

Project Structure (Package Explorer view in Eclipse)

1_RestEasy-Spring-MVC-Hibernate_Project_Structure_In_Eclipse

Jars Libraries Used in the Project (Maven Dependencies)

2_RestEasy-Spring-MVC-Hibernate_Jars_In_Classpath

Database: Creating table and inserting few records for this example

Create Table command

CREATE TABLE `CUSTOMER` (
  `CUSTOMER_ID` INT(6) NOT NULL AUTO_INCREMENT,
  `NAME` VARCHAR(50) NOT NULL,
  `AGE` INT(3) NOT NULL,
  PRIMARY KEY (`CUSTOMER_ID`)
);

Insert command (examples)

INSERT INTO `CUSTOMER`(`NAME`, `AGE`) VALUES ("Tom", 26);
INSERT INTO `CUSTOMER`(`NAME`, `AGE`) VALUES ("Dick", 27);
INSERT INTO `CUSTOMER`(`NAME`, `AGE`) VALUES ("Harry", 28);
INSERT INTO `CUSTOMER`(`NAME`, `AGE`) VALUES ("Henny", 21);
INSERT INTO `CUSTOMER`(`NAME`, `AGE`) VALUES ("Esbita", 19);

Web application

For any web application, entry point is web.xml which describes how the incoming http requests are served / processed. Further, it describes about the global-context and local-context param (i.e.; <context-param> & <init-param>) for loading files particular to project requirements & contains respective listener

With this introduction, we will understand how we configured web.xml for RestEasy JAX-RS Restful web service

web.xml (the entry point –> under WEB-INF)

This web.xml file describes,

  • any http requests with pattern “/resteasy/*” will be intercepted by the configured servlet called “DispatcherServlet” (org.springframework.web.servlet.DispatcherServlet)
  • <servlet-name> name mentioned in the web.xml is “spring-mvc-resteasy”, which on loading/exploading the war into application server(Tomcat server for our example) looks for the servlet filename called “springmvc-hibernate-resteasy-servlet.xml
  • <context-param> with its attributes describes the location of the “springmvc-hibernate-resteasy-servlet.xml” file from where it has to be loaded. We will discuss briefly about this file
  • <welcome-file-list> files under this tag is the start-up page

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

	<display-name>RestEasy-Spring-MVC-Hibernate</display-name>

	<!-- Spring MVC Dispatcher Servlet -->
	<servlet>
		<servlet-name>springmvc-hibernate-resteasy</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc-hibernate-resteasy</servlet-name>
		<url-pattern>/resteasy/*</url-pattern>
	</servlet-mapping>

	<!-- loading Spring Context for registering beans with ApplicationContext -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>WEB-INF/springmvc-hibernate-resteasy-servlet.xml</param-value>
	</context-param>

	<!-- welcome file -->
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

</web-app>

Spring Application Context file

This Spring Application Context file describes,

  • import “springmvc-resteasy.xml” configuration file which specifies default RestEasy + Spring MVC Integration beans
  • <context:annotation-config /> to activate annotation on the registered beans with application context
  • <mvc:annotation-driven /> to explicit support for annotation-driven MVC controllers
  • <context:component-scan base-package=”” /> tag scans all classes & sub-classes under the value of base-package attribute and register them with the Spring container (i.e.; to scan for Spring MVC annotations)
  • Basically these classes are annotated with @Controller on top of the class
  • bean with id=”transactionManager” to inform spring to take care of the database transaction. All methods annotated with @Transactional
  • <tx:annotation-driven /> to turn ON transaction annotation on all DAO methods
  • bean with id=”sessionFactory” defines hibernate properties to let it take care of database operations using hibernate’s rich API
  • bean with id=”dataSource” defines values for driverClassName, url, username and password for MySql database
  • Note: injection series between transactionManager, sessionFactory and dataSource
  • bean id=“viewResolver” defines the logic for view resolver i.e.; viewName returned by the Controller which will be sandwiched between the prefix (WEB-INF/jsp) & suffix (.jsp)
  • Now, there should be a file under the directory as defined i.e.; (WEB-INF/jsp/<viewName>.jsp
  • Otherwise, not found exception thrown

springmvc-hibernate-resteasy-servlet.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:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<!-- Import basic SpringMVC Resteasy integration -->
	<import resource="classpath:springmvc-resteasy.xml" />

	<!-- to activate annotations in beans already registered in the ApplicationContext -->
	<context:annotation-config />

	<!-- to activate MVC annotation -->
	<mvc:annotation-driven />

	<!-- scans packages to find and register beans within the ApplicationContext -->
	<context:component-scan base-package="com.resteasy.series.spring.mvc.hibernate" />

	<!-- turn on spring transaction annotation -->
	<tx:annotation-driven transaction-manager="transactionManager" />

	<!-- Transaction Manager -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!-- Session Factory -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="annotatedClasses">
			<list>
				<value>com.resteasy.series.spring.mvc.hibernate.model.Customer</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>

	<!-- dataSource configuration -->
	<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/benchresources" />
		<property name="username" value="root" />
		<property name="password" value="" />
	</bean>

	<!-- view resolver -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

 

Let’s see coding in action

 

URL Pattern

Http url for any common web application is http://<server>:<port>/<root-context>/<from_here_application_specific_path>

In our example, we are going to deploy the war into Tomcat 7.0 server so our server and port are localhost and 8080 respectively. Context root is the project name i.e.; RestEasy-Spring-Hibernate. Initial path for this application is http://localhost:8080/RestEasy-Spring-MVC-Hibernate

We have configured “/resteasy/*” as url-pattern for the “javax.ws.rs.core.Application” servlet in web.xml and at interface-level (or say class-level) path configured is “/resteasy/customerservice” using @Path annotation. Next respective path for each method annotated with @Path (method-level)

Model Class

Model class Customer with three primitive attributes with their getter/setter && no-arg constructor and 3-arg constructor

Also Hibernate POJO class is annotated describing the mapping between java property and database columns

@Entity:  represents an object that can be persisted in the database and for this class should have no-arg constructor
@Table: describes which table in the database to map with this class properties
@Id: defines this is unique which means it represents primary key in the database table
@GeneratedValue: this will be taken care by hibernate to define generator sequence
@Column: tells to map this particular property to table column in the database
For example, “age” property used to map “AGE” column in the “CUSTOMER” table in the database
@Column(name= “AGE”)
                        private int age;

Note: we can add attributes to the @Column annotation like name, length, nullable and unique

Customer.java

package com.resteasy.series.spring.mvc.hibernate.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 {

	// member variables
	@Id
	@GeneratedValue
	@Column(name = "CUSTOMER_ID")
	private int customerId;

	@Column(name= "NAME")
	private String name;

	@Column(name= "AGE")
	private int age;

	// default constructor
	public Customer() {
		super();
	}

	// 3-arg parameterized-constructor
	public Customer(int customerId, String name, int age) {
		super();
		this.customerId = customerId;
		this.name = name;
		this.age = age;
	}

	// getters & setters
	public int getCustomerId() {
		return customerId;
	}
	public void setCustomerId(int customerId) {
		this.customerId = customerId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

Customer Service interface

 Defines simple CURD operations

  • @POST – create/inserts a new resource (new customer)
  • @GET – read/selects internal resource representation based on the customerId
  • @GET – retrieves all players (get all customers)
  • @GET – returns ModelAndView objects with viewName and objects to be rendered on the front end JSP page

Let’s discuss @Produces, @Consumes and MediaType

@Consumes
Defines which MIME type is consumed by this method. For this example, exposed methods supports both XML & JSON formats i.e.; methods are annotated with @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})

Note: When Content-Type is not specified in the header, then by default it expects request body in “application/x-www-form-urlencoded”. So, Content-Type needs to be set/sent in the header

@Produces
Defines which MIME type it will produce. For this example, exposed methods produce response in both XML & JSON formats i.e.; methods are annotated with @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})

Note: By default, when invoked it returns the response in XML as it is the first string in the array. So, to get the response in the JSON format then set accept=”application/json” in the header

Most widely used Media Types are

  • MediaType.APPLICATION_XML,
  • MediaType.APPLICATION_JSON,
  • MediaType.TEXT_HTML,
  • MediaType.TEXT_PLAIN,
  • MediaType.TEXT_XML,
  • MediaType.APPLICATION_FORM_URLENCODED,
  • etc

NOTE: It’s always a good programming practice to do code-to-interface and have its implementation separately

ICustomerService.java

package com.resteasy.series.spring.mvc.hibernate.service;

import in.benchresources.cdm.customer.CustomerListType;
import in.benchresources.cdm.customer.CustomerType;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.springframework.web.servlet.ModelAndView;

@Path("/resteasy/customerservice")
public interface ICustomerService {

	// Basic CRUD operations for Customer Service

	// http://localhost:8080/RestEasy-Spring-MVC-Hibernate/resteasy/customerservice/addcustomer  - Tomcat 7.0.x
	// http://localhost:9090/RestEasy-Spring-MVC-Hibernate/resteasy/customerservice/addcustomer  - JBoss AS7
	@POST
	@Path("addcustomer")
	@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	@Produces({MediaType.APPLICATION_FORM_URLENCODED})
	public String createOrSaveNewCustomerInfo(CustomerType customerType);

	// http://localhost:8080/RestEasy-Spring-MVC-Hibernate/resteasy/customerservice/getcustomer/10001  - Tomcat 7.0.x
	// http://localhost:9090/RestEasy-Spring-MVC-Hibernate/resteasy/customerservice/getcustomer/10001  - JBoss AS7
	@GET
	@Path("getcustomer/{id}")
	@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	public CustomerType getCustomerInfo(@PathParam("id") int customerId);

	// http://localhost:8080/RestEasy-Spring-MVC-Hibernate/resteasy/customerservice/getallcustomer  - Tomcat 7.0.x
	// http://localhost:9090/RestEasy-Spring-MVC-Hibernate/resteasy/customerservice/getallcustomer  - JBoss AS7
	@GET
	@Path("getallcustomer")
	@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	public CustomerListType getAllCustomerInfo();

	// REST allows a client to select which format it prefers to receive the data in through a process called Content Negotiation.
	// Content Negotiation can happen through HTTP headers, URI or query parameters.

	// http://localhost:8080/RestEasy-Spring-MVC-Hibernate/resteasy/customerservice/viewallcustomer  - Tomcat 7.0.x
	// http://localhost:9090/RestEasy-Spring-MVC-Hibernate/resteasy/customerservice/viewallcustomer  - JBoss AS7
	@GET
	@Path("viewallcustomer")
	@Produces(MediaType.TEXT_HTML)
	public ModelAndView viewAllCustomer();
}

Customer Service implementation

Implements above interface. JAX-RS classes should be annotated with Spring annotation like @Component or @Service

CustomerServiceImpl.java

package com.resteasy.series.spring.mvc.hibernate.service;

import in.benchresources.cdm.customer.CustomerListType;
import in.benchresources.cdm.customer.CustomerType;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import com.resteasy.series.spring.mvc.hibernate.dao.CustomerDAO;
import com.resteasy.series.spring.mvc.hibernate.model.Customer;

@Controller
public class CustomerServiceImpl implements ICustomerService {

	@Autowired
	private CustomerDAO customerDAO;

	@Override
	public String createOrSaveNewCustomerInfo(CustomerType customerType) {

		Customer newCustomer = new Customer();
		newCustomer.setCustomerId(customerType.getCustomerId());
		newCustomer.setName(customerType.getName());
		newCustomer.setAge(customerType.getAge());
		return customerDAO.insertNewCustomer(newCustomer);
	}

	@Override
	public CustomerType getCustomerInfo(int customerId) {

		Customer getCustomer = customerDAO.getCustomer(customerId);

		CustomerType customerType = new CustomerType();
		customerType.setCustomerId(getCustomer.getCustomerId());
		customerType.setName(getCustomer.getName());
		customerType.setAge(getCustomer.getAge());
		return customerType;
	}

	@Override
	public CustomerListType getAllCustomerInfo() {

		List<Customer> lstCustomer = customerDAO.getAllCustomer();
		CustomerListType customerListType = new CustomerListType();

		for(Customer customer : lstCustomer){
			CustomerType customerType = new CustomerType();
			customerType.setCustomerId(customer.getCustomerId());
			customerType.setName(customer.getName());
			customerType.setAge(customer.getAge());
			customerListType.getCustomerType().add(customerType);
		}
		return customerListType;
	}

	@Override
	public ModelAndView viewAllCustomer() {

		CustomerListType customerListType = getAllCustomerInfo();
		return new ModelAndView("viewAllCustomer", "customerListType", customerListType);
	}
}

DAO layer

This DAO layer takes care of the database interaction i.e.; uses Hibernate’s rich API to interact with MySql database using MySqlDialect

CustomerDAO.java

package com.resteasy.series.spring.mvc.hibernate.dao;

import java.util.List;

import com.resteasy.series.spring.mvc.hibernate.model.Customer;

public interface CustomerDAO {

	public String insertNewCustomer(Customer customer);
	public Customer getCustomer(int customerId);
	public List<Customer> getAllCustomer();
}

CustomerDAOImpl.java

package com.resteasy.series.spring.mvc.hibernate.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.resteasy.series.spring.mvc.hibernate.model.Customer;

@Repository("customerDAO")
public class CustomerDAOImpl implements CustomerDAO	 {

	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	@Transactional
	public String insertNewCustomer(Customer customer) {

		// inserts into database & return customerId (primary_key)
		int customerId = (Integer) sessionFactory.getCurrentSession().save(customer);
		return "Customer information saved successfully with Customer_ID " + customerId;
	}

	@Override
	@Transactional
	public Customer getCustomer(int customerId) {

		// retrieve customer based on the id supplied in the formal argument
		Customer customer = (Customer) sessionFactory.getCurrentSession().get(Customer.class, customerId);
		return customer;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public List<Customer> getAllCustomer() {

		// get all customer info from database
		List<Customer> lstCustomer = sessionFactory.getCurrentSession().createCriteria(Customer.class).list();
		return lstCustomer;
	}
}

 

View Technologies

 

Start up page which has anchor link to “resteasy/customerservice/viewallcustomer” with value “View All Customers” à redirects to Controller method viewAllCustomer() which returns ModelAndView with viewName “viewAllCustomers

index.html (\src\main\webapp\index.html)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>RestEasy-Spring-MVC-Hibernate</title>
</head>
<body style="text-align: center">
	<br />
	<br />
	<b>Welcome to the world of RestEasy - A JAX-RS Restful web service</b>
	<br />
	<br />
	<a href="resteasy/customerservice/viewallcustomer">View All
		Customers</a>
</body>
</html>

 

On clicking link “View All Customers” on the index page invokes controller method, to return ModelAndView object with viewName which is “viewAllCustomer” i.e.; below JSP page along with customerListType objects containing all customer details. This objects is rendered and data is displayed in this JSP page in table format

viewAllCustomers.jsp (\src\main\webapp\WEB-INF\jsp\viewAllCustomers.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>RestEasy-Spring-MVC-Hibernate</title>
</head>
<body style="text-align: center">
	<h4>View All Customers</h4>
	<table align="center" border="1" cellpadding="10">
		<tr>
			<th>Customer ID</th>
			<th>Name</th>
			<th>Age</th>
		</tr>
		<c:forEach items="${customerListType.customerType}" var="customerType"
			varStatus="status">
			<tr>
				<td>${customerType.customerId}</td>
				<td>${customerType.name}</td>
				<td>${customerType.age}</td>
			</tr>
		</c:forEach>
	</table>
	<br />
</body>
</html>

 

Deployment

  • Run maven command to build the war: mvn clean install (use command prompt or integrated maven in eclipse IDE
  • Copy the war file from the target folder
  • Paste it into apache tomcat (webapps folder)
  • Start the tomcat server

Test the service !!

 

Testing

There are many ways to do testing

  • Copy the URL of GET service into web browser
  • Advanced REST client from Google Chrome
  • Rest client in Mozilla Firefox Add On
  • Write your own client for example, Java client using improved CloseableHttpClient from Apache
  • JDK’s in-built classes like HttpURLConnection
  • Using Client, WebTarget from core JAX-RS classes javax.ws.rs.client
  • Using ResteasyClient, ResteasyWebTarget and Response classes from JBoss package org.jboss.resteasy.client
  • Using ClientRequest and ClientResponse classes from JBoss package org.jboss.resteasy.client

 

1. Spring MVC + RestEasy

Enter base URL into web browser http://localhost:8080/RestEasy-Spring-MVC-Hibernate –> which has a link to view all customers

3_RestEasy-Spring-MVC-Hibernate_index_page

Click the link –> hits the service viewAllCustomer() and returns ModelAndView objects and thus displays below page

4_RestEasy-Spring-MVC-Hibernate_view_all_customers_page

 

2. Java client (RestEasy)

There are two test clients which comes from JBoss RestEasy package org.jboss.resteasy.client and org.jboss.resteasy.client.jaxrs

  1. ClientRequest and ClientResponse for invoking getCustomerInfo service
  2. ResteasyClient, ResteasyClientBuilder and ResteasyWebTarget for invoking addCustomerInfo service

Self-explanatory !!

Note: above clients can be interchanged. No restriction, only needs to set correct http request parameters or header values

TestCustomerService.java

package test.resteasy.series.spring.mvc.hibernate.service;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

public class TestCustomerService {

	public static void main(String[] args) throws Exception {

		// setting & invoking first service getCustomer/45001
		System.out.println("Invoking and executing getCustomer service for customer id 14");
		String httpGetURL = "http://localhost:8080/RestEasy-Spring-MVC-Hibernate/resteasy/customerservice/getcustomer/14";
		String responseStringGet = testCustomerServiceForGetRequest(httpGetURL);
		System.out.println("GET >> Response String : " + responseStringGet);

		// setting & invoking second service addCustomer with XML request
		System.out.println("\n\nInvoking and executing addCustomer service with request");
		String httpPostURL = "http://localhost:8080/RestEasy-Spring-MVC-Hibernate/resteasy/customerservice/addcustomer";
		String requestStringInXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
				+ 					"<CustomerType xmlns=\"http://benchresources.in/cdm/Customer\">"
				+ 						"<customerId>15</customerId>"
				+ 						"<name>Spider Man</name>"
				+ 						"<age>21</age>"
				+ 					"</CustomerType>";
		String requestStringInJson = "{"
				+ 						" \"customerId\": 16, "
				+ 						" \"name\": \"Jerry\","
				+ 						"\"age\": 25 "
				+					"}";
		String responseStringPost = testCustomerServiceForPostRequest(httpPostURL, requestStringInXml);
		System.out.println("POST >> Response String : " + responseStringPost);
	}

	/**
	 * using ClientRequest and ClientResponse classes from org.jboss.resteasy.client
	 * @param httpURL
	 * @return responseString
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public static String testCustomerServiceForGetRequest(String httpURL) throws Exception {

		// local variables
		ClientRequest clientRequest = null;
		ClientResponse<String> clientResponse = null;
		int responseCode;
		String responseString = null;

		try{
			clientRequest = new ClientRequest(httpURL);
			clientRequest.setHttpMethod(HttpMethod.GET);
			clientRequest.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
			clientRequest.accept(MediaType.APPLICATION_XML);
			clientResponse = clientRequest.get(String.class);

			responseCode = clientResponse.getResponseStatus().getStatusCode();
			System.out.println("Response code: " + responseCode);

			if(clientResponse.getResponseStatus().getStatusCode() != 200) {
				throw new RuntimeException("Failed with HTTP error code : " + responseCode);
			}

			System.out.println("ResponseMessageFromServer: " + clientResponse.getResponseStatus().getReasonPhrase());
			responseString = clientResponse.getEntity();
		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
		finally{
			// release resources, if any
			clientResponse.close();
			clientRequest.clear();
		}
		return responseString;
	}

	/**
	 * using ResteasyClient, ResteasyWebTarget and Response classes from org.jboss.resteasy.client
	 * @param httpURL
	 * @param requestString
	 * @return
	 */
	public static String testCustomerServiceForPostRequest(String httpURL, String requestString)  throws Exception {

		// local variables
		ResteasyClient resteasyClient = null;
		ResteasyWebTarget resteasyWebTarget = null;
		Response response = null;
		int responseCode;
		String responseString = null;

		try{
			resteasyClient = new ResteasyClientBuilder().build();
			resteasyWebTarget = resteasyClient.target(httpURL);
			//			resteasyWebTarget.property("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
			//			resteasyWebTarget.property("accept", MediaType.APPLICATION_XML);
			response = resteasyWebTarget.request(MediaType.APPLICATION_FORM_URLENCODED).post(Entity.entity(requestString, MediaType.APPLICATION_XML));

			responseCode = response.getStatus();
			System.out.println("Response code: " + responseCode);

			if (response.getStatus() != 200) {
				throw new RuntimeException("Failed with HTTP error code : " + responseCode);
			}

			System.out.println("ResponseMessageFromServer: " + response.getStatusInfo().getReasonPhrase());
			responseString = response.readEntity(String.class);
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		finally{
			// release resources, if any
			response.close();
		}
		return responseString;
	}
}

Output in console

Invoking and executing getCustomer service for customer id 14
Response code: 200
ResponseMessageFromServer: OK
GET >> Response String : 
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<CustomerType xmlns="http://benchresources.in/cdm/Customer">
	<customerId>14</customerId>
	<name>Clinton</name>
	<age>54</age>
</CustomerType>

Invoking and executing addCustomer service with request
Response code: 200
ResponseMessageFromServer: OK
POST >> Response String : Customer information saved successfully with Customer_ID 15

Note: Study java client and do necessary changes to test other exposed services

Download project (Tomcat Server 7.0.x)

RestEasy-Spring-MVC-Hibernate(Tomcat server) (17kB)

 

JBoss Deployment

  1. Update pom.xml with resteasy scope “provided” for dependencies as JBoss AS7 modules already contains these dependent jars
    <resteasy.scope>provided</resteasy.scope> <!-- compile(Tomcat) / provided(JBoss) -->
    
  2. Rest remain the same
  3. Read through this article which explains development & deployment of RestEasy web service with JBoss Application Server in detail

Note: JBoss Application Server 7.1.1.Final comes with default RestEasy distribution with version 2.3.2.Final. So update JBoss AS7 with latest RestEasy version. Look at this article, which explains how to update default version with latest version available in the JBoss community

Download project (JBoss Application Server 7.1.1.Final)

RestEasy-Spring-MVC-Hibernate(JBoss server) (17kB)

Conclusion: Thus, we have successfully integrated hibernate ORM framework with RestEasy + Spring MVC

Happy Coding !!
Happy Learning !!

RestEasy: JAX-RS web service + Integrating with Spring Security
RestEasy: JAX-RS web service + Integrating with Spring MVC web framework