In this article, we will extend previous article and integrate with Spring & Hibernate for database interaction. In the previous article, constructed a dummy objects for web service. But here we will use Hibernate’s rich API to interact with MySql database or in general any ORM compliant database
Jersey is the most popular amongst Restful web service development. Latest Jersey 2.x version has been developed by Oracle/Glassfish team in accordance with JAX-RS 2.0 specification. Earlier Jersey 1.x version was developed and supported by Oracle/Sun team
Latest Jersey release version is 2.12 see here and look documentation and API for details. We will implement Jersey examples in the following articles based on latest 2.x version
As we are going to use both XML & JSON for web service request/response, we will design XSD for our service. Then invoke the services of Maven’s JAXB plugin to generate java-sources, as this is considered standard
Note: It’s a good practice to design XSD, if one intended to use XML for web service request/response
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)
- @Component (springframework.stereotype.Component)
- @Repository (springframework.stereotype.Repository)
- MediaType (ws.rs.core.MediaType)
Technology Used
- Java 1.7
- Eclipse Luna IDE
- Jersey-2.12
- Jersey-spring3-2.12
- Spring framework-4.1.0.RELEASE
- Hibernate-4.3.6.Final
- MySql-connector-java-5.1.32
- Apache Maven 3.2.1
- Apache Tomcat 8.0.54
- Glassfish-4.1
Mavenize or download required jars
Add Jersey-2.12, Jersey-spring3-2.12, Spring-4.1.0.RELEASE, Hibernate-4.3.6.Final & mysql-5.1.32 dependencies to pom.xml
<properties> <jersey.version>2.12</jersey.version> <jersey.scope>compile</jersey.scope> <spring.version>4.1.0.RELEASE</spring.version> <hibernate.version>4.3.6.Final</hibernate.version> <mysql.version>5.1.32</mysql.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> <!-- Jersey core Servlet 2.x implementation --> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet-core</artifactId> <version>${jersey.version}</version> <scope>${jersey.scope}</scope> </dependency> <!-- Jersey JSON Jackson (2.x) entity providers support module --> <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-jackson</artifactId> <version>${jersey.version}</version> <scope>${jersey.scope}</scope> </dependency> <!-- Jersey extension module providing support for Spring 3 integration --> <dependency> <groupId>org.glassfish.jersey.ext</groupId> <artifactId>jersey-spring3</artifactId> <version>${jersey.version}</version> <scope>${jersey.scope}</scope> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </exclusion> </exclusions> </dependency> <!-- Spring Framework-4.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 4.2.x --> <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> </dependencies>
Note: Jackson – high performance parser is included as dependencies for JSON support
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 include them in the classpath
- jersey-container-servlet-core
- javax.ws.rs-api-2.0.1
- jersey-server-2.12
- jersey-common-2.12
- jersey-client-2.12
- jersey-guava-2.12
- javax-annotation-api-1.2
- javax.inject-2.3.0-b10
- hk2-api-2.3.0-b10
- hk2-utils-2.3.0-b10
- aop-alliance-repackaged-2.3.0-b10
- hk2-locator
- javassist-3.18.1-GA
- validation-api-1.1.0.Final
- osgi-resource-locator-1.0.1
- jersey-media-json-jackson
- jackson-jaxrs-base-2.3.2
- jackson-core-2.3.2
- jackson-databind-2.3.2
- jackson-jaxb-json-provider-2.3.2
- jackson-annotation-2.3.2
- jackson-module-jaxb-annotation-2.3.2
- jersey-spring3
- spring-framework-4.1.0.RELEASE
- hibernate-4.3.6.Final
- mysql-connector-java-5.1.32
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/jersey/series/spring/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>
Book.xsd
Below XSD contains two elements with name “BookType” and “BookListType”
- BookType contains four attributes namely bookId, bookName, author, category
- BookListType which returns list of BookType
<?xml version="1.0" encoding="UTF-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://benchresources.in/cdm/Book" xmlns:tns="http://benchresources.in/cdm/Book" elementFormDefault="qualified"> <!-- book object with four attributes --> <xsd:element name="BookType"> <xsd:complexType> <xsd:sequence> <xsd:element name="bookId" type="xsd:int" /> <xsd:element name="bookName" type="xsd:string" /> <xsd:element name="author" type="xsd:string" /> <xsd:element name="category" type="xsd:string" /> </xsd:sequence> </xsd:complexType> </xsd:element> <!-- an object to contain lists of books referencing above Book object --> <xsd:element name="BookListType"> <xsd:complexType> <xsd:sequence> <xsd:element ref="tns:BookType" 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
BookType.java
package in.benchresources.cdm.book; 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 = { "bookId", "bookName", "author", "category" }) @XmlRootElement(name = "BookType") public class BookType { protected int bookId; @XmlElement(required = true) protected String bookName; @XmlElement(required = true) protected String author; @XmlElement(required = true) protected String category; public int getBookId() { return bookId; } public void setBookId(int value) { this.bookId = value; } public String getBookName() { return bookName; } public void setBookName(String value) { this.bookName = value; } public String getAuthor() { return author; } public void setAuthor(String value) { this.author = value; } public String getCategory() { return category; } public void setCategory(String value) { this.category = value; } }
BookListType.java
package in.benchresources.cdm.book; 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 = { "bookType" }) @XmlRootElement(name = "BookListType") public class BookListType { @XmlElement(name = "BookType") protected List<BookType> bookType; public List<BookType> getBookType() { if (bookType == null) { bookType = new ArrayList<BookType>(); } return this.bookType; } }
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)
Jars Libraries Used in the Project (Maven Dependencies)
Database: Creating table and inserting few records for this example
Create Table command
CREATE TABLE `BOOK` ( `BOOK_ID` INT(6) NOT NULL AUTO_INCREMENT, `BOOK_NAME` VARCHAR(50) NOT NULL, `AUTHOR` VARCHAR(50) NOT NULL, `CATEGORY` VARCHAR(50) NOT NULL, PRIMARY KEY (`BOOK_ID`) );
Insert command (examples)
INSERT INTO `book`(`BOOK_NAME`, `AUTHOR`, `CATEGORY`) VALUES ('Diagnostic Microbiology', 'Patricia Tille', 'Microbiology'); INSERT INTO `book`(`BOOK_NAME`, `AUTHOR`, `CATEGORY`) VALUES ('Microbiology Coloring Book', 'I. Edward Alcamo', 'Microbiology'); INSERT INTO `book`(`BOOK_NAME`, `AUTHOR`, `CATEGORY`) VALUES ('Medical Microbiology and Infection', 'Stephen Gillespie', 'Microbiology'); INSERT INTO `book`(`BOOK_NAME`, `AUTHOR`, `CATEGORY`) VALUES ('Essential Microbiology and Hygiene for Food', 'Sibel Roller', 'Microbiology'); INSERT INTO `book`(`BOOK_NAME`, `AUTHOR`, `CATEGORY`) VALUES ('Revenge-of-Microbes', 'Abigail', 'Microbiology');
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 Jersey JAX-RS Restful web service
web.xml (the entry point –> under WEB-INF)
This web.xml file describes,
- Like any JEE web framework register “org.glassfish.jersey.servlet.ServletContainer” with servlet container
- register spring listener springframework.web.context.ContextLoaderListener
- http requests with URL pattern “/rest/*” will be sent to the registered servlet called “jersey-servlet” i.e.; (org.glassfish.jersey.servlet.ServletContainer)
- Set <init-param> with <param-name> as “jersey.config.server.provider.packages” and <param-value> describing the qualified package name of the JAX-RS annotated Resource/Provider classes. In this example, “com.jersey.series.spring.hibernate.service”
- <context-param> with its attributes describes the location of the “spring-hibernate-jersey2.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>Jersey-Spring-Hibernate</display-name> <!-- Spring Listener --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Jersey Servlet --> <servlet> <servlet-name>jersey-servlet</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <!-- Register resources and providers --> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>com.jersey.series.spring.hibernate.service</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey-servlet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> <!-- loading Spring Context for registering beans with ApplicationContext --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/spring-hibernate-jersey2.xml</param-value> </context-param> <!-- welcome file --> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
Spring Application Context file
This Spring Application Context file describes,
- <context:annotation-config /> to activate annotation on the registered beans with application context
- <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
- 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
spring-hibernate-jersey2.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" 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-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- to activate annotations in beans already registered in the ApplicationContext --> <context:annotation-config /> <!-- scans packages to find and register beans within the application context --> <context:component-scan base-package="com.jersey.series.spring.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.jersey.series.spring.hibernate.model.Book</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> </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 8.0 server so our server and port are localhost and 8080 respectively. Context root is the project name i.e.; Jersey-Spring-Hibernate. Initial path for this application is http://localhost:8080/Jersey-Spring-Hibernate
We have configured “/rest/*” as url-pattern for the “jersey-servlet” servlet in web.xml and at class-level path configured is “/bookservice” using @Path annotation. Next respective path for each method annotated with @Path (method-level)
Model Class (POJO)
Model class Book with four primitive attributes with their getter/setter
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, “bookId” property used to map “BOOK_ID” column in the “BOOK” table in the database
@Column(name= “BOOK_ID”)
private int bookId;
Note: we can add attributes to the @Column annotation like name, length, nullable and unique
Book.java
package com.jersey.series.spring.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 = "BOOK") public class Book { // member variables @Id @GeneratedValue @Column(name = "BOOK_ID") private int bookId; @Column(name= "BOOK_NAME") private String bookName; @Column(name= "AUTHOR") private String author; @Column(name= "CATEGORY") private String category; // getters & setters public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
Book Service interface
Defines basic CRUD operations for Book Service
NOTE: It’s always a good programming practice to do code-to-interface and have its implementation separately
IBookService.java
package com.jersey.series.spring.hibernate.service; import in.benchresources.cdm.book.BookListType; import in.benchresources.cdm.book.BookType; public interface IBookService { // Basic CRUD operations for Book Service public String createOrSaveBookInfo(BookType bookType); public BookType getBookInfo(int bookId); public String updateBookInfo(BookType bookType); public String deleteBookInfo(int bookId); public BookListType getAllBookInfo(); }
Book Service implementation
Implements above interface
Defines simple CURD operations
- @POST – create/inserts a new resource (adds new book information)
- @GET – read/selects internal resource representation based on the bookId
- @PUT – update/modifies an internal resource representation (modify book)
- @DELETE – delete/removes a resource (delete book)
- @GET – retrieves all books (get all books information)
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
- APPLICATION_XML,
- APPLICATION_JSON,
- TEXT_PLAIN,
- TEXT_XML,
- APPLICATION_FORM_URLENCODED,
- etc
Note: Jersey doesn’t inherit JAX-RS annotations. So we are annotating Resource/Provider classes and then defining qualified package name in web.xml
BookServiceImpl.java
package com.jersey.series.spring.hibernate.service; import java.util.List; import in.benchresources.cdm.book.BookListType; import in.benchresources.cdm.book.BookType; 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.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.jersey.series.spring.hibernate.dao.BookDAO; import com.jersey.series.spring.hibernate.model.Book; @Component @Path("/bookservice") public class BookServiceImpl implements IBookService { @Autowired private BookDAO bookDAO; // Basic CRUD operations for Book Service // http://localhost:8080/Jersey-Spring-Hibernate/rest/bookservice/addbook @POST @Path("addbook") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces(MediaType.APPLICATION_FORM_URLENCODED) public String createOrSaveBookInfo(BookType bookType) { // unwrap bookType and set in Model object Book Book newBook = new Book(); newBook.setBookId(bookType.getBookId()); newBook.setBookName(bookType.getBookName()); newBook.setAuthor(bookType.getAuthor()); newBook.setCategory(bookType.getCategory()); return bookDAO.insertNewBookInfo(newBook); } // http://localhost:8080/Jersey-Spring-Hibernate/rest/bookservice/getbook/1 @GET @Path("getbook/{id}") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public BookType getBookInfo(@PathParam("id") int bookId) { // retrieve book information based on the id supplied in the formal argument Book getBook = bookDAO.getBookInfo(bookId); BookType bookType = new BookType(); bookType.setBookId(getBook.getBookId()); bookType.setBookName(getBook.getBookName()); bookType.setAuthor(getBook.getAuthor()); bookType.setCategory(getBook.getCategory()); return bookType; } // http://localhost:8080/Jersey-Spring-Hibernate/rest/bookservice/updatebook @PUT @Path("updatebook") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces(MediaType.APPLICATION_FORM_URLENCODED) public String updateBookInfo(BookType bookType) { // unwrap bookType and set in Model object Book Book modifyBook = new Book(); modifyBook.setBookId(bookType.getBookId()); modifyBook.setBookName(bookType.getBookName()); modifyBook.setAuthor(bookType.getAuthor()); modifyBook.setCategory(bookType.getCategory()); // update book info & return SUCCESS message return bookDAO.updateBookInfo(modifyBook); } // http://localhost:8080/Jersey-Spring-Hibernate/rest/bookservice/deletebook/5 @DELETE @Path("deletebook/{id}") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_FORM_URLENCODED) public String deleteBookInfo(@PathParam("id") int bookId) { // delete book info & return SUCCESS message Book removeBook = new Book(); removeBook.setBookId(bookId); return bookDAO.removeBookInfo(removeBook); } // http://localhost:8080/Jersey-Spring-Hibernate/rest/bookservice/getallbook @GET @Path("getallbook") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public BookListType getAllBookInfo() { List<Book> lstBook = bookDAO.getAllBookInfo(); // create a object of type BookListType which takes book objects in its list BookListType bookListType = new BookListType(); for(Book book : lstBook){ BookType bookType = new BookType(); bookType.setBookId(book.getBookId()); bookType.setBookName(book.getBookName()); bookType.setAuthor(book.getAuthor()); bookType.setCategory(book.getCategory()); bookListType.getBookType().add(bookType); // add to bookListType } return bookListType; } }
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
BookDAO.java
package com.jersey.series.spring.hibernate.dao; import java.util.List; import com.jersey.series.spring.hibernate.model.Book; public interface BookDAO { public String insertNewBookInfo(Book addBook); public Book getBookInfo(int bookId); public String updateBookInfo(Book updateBook); public String removeBookInfo(Book removeBook); public List<Book> getAllBookInfo(); }
BookDAOImpl.java
package com.jersey.series.spring.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.jersey.series.spring.hibernate.model.Book; @Repository("bookDAO") public class BookDAOImpl implements BookDAO { @Autowired private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override @Transactional public String insertNewBookInfo(Book book) { // inserts into database & return bookId (primary_key) int bookId = (Integer) sessionFactory.getCurrentSession().save(book); return "Book information saved successfully with Book_ID " + bookId; } @Override @Transactional public Book getBookInfo(int bookId) { // retrieve book object based on the id supplied in the formal argument Book book = (Book) sessionFactory.getCurrentSession().get(Book.class, bookId); return book; } @Override @Transactional public String updateBookInfo(Book updateBook) { // update database with book information and return success msg sessionFactory.getCurrentSession().update(updateBook); return "Book information updated successfully"; } @Override @Transactional public String removeBookInfo(Book removeBook) { // delete book information and return success msg sessionFactory.getCurrentSession().delete(removeBook); return "Book information with Book_ID " + removeBook.getBookId() + " deleted successfully"; } @SuppressWarnings("unchecked") @Override @Transactional public List<Book> getAllBookInfo() { // get all books info from database List<Book> lstBook = sessionFactory.getCurrentSession().createCriteria(Book.class).list(); return lstBook; } }
Tomcat-8.0.12 Deployment
- Run maven command to build the war: mvn clean install (use command prompt or integrated maven in eclipse IDE
- Copy(ctrl+c) the war file from the target folder
- Paste(ctrl+v) it into apache tomcat (webapps folder)
- Start the tomcat server
Glassfish-4.1 Deployment
- Run maven command to build the war: mvn clean install (use command prompt or integrated maven in eclipse IDE
- Once you see “BUILD SUCCESS” after running maven command, keep the war file ready to be deployed
- There are two ways to deploy war file into Glassfish-4.1
- Online
- Offline
- Click here to understand above deployments process in detail
Test the service !!
Testing
There are many ways to do testing
- Access html page from web browser
- 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
1. Using RestClient from Mozilla Firefox Add-On
Every service tested setting up header parameters “accept” & “Content-Type” in the request. First for JSON format and then XML format
First service: @POST (createOrSaveBookInfo())
URL: http://localhost:8080/Jersey-Spring-Hibernate/rest/bookservice/addbook
Request:
{ "bookId": 8, "bookName": "Molecular Biology of The Gene", "author": "James D Watson", "category": "Microbiology" }
Content-Type: application/json
Accept: application/x-www-form-urlencoded
Response: New Book information saved successfully with Book_ID 8
Request:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <BookType xmlns="http://benchresources.in/cdm/Book"> <bookId>7</bookId> <bookName>Diagnostic Microbiology</bookName> <author>Patricia Tille</author> <category>Microbiology</category> </BookType>
Content-Type: application/xml
Accept: application/x-www-form-urlencoded
Response: New Book information saved successfully with Book_ID 7
Second service: @GET (getBookInfo())
URL: http://localhost:8080/Jersey-Spring-Hibernate/rest/bookservice/getbook/1
Request: None
Content-Type: application/x-www-form-urlencoded
Accept: application/json
Response:
{ "bookId": 1, "bookName": "Diagnostic Microbiology", "author": "Patricia Tille", "category": "Microbiology" }
Request: None
Content-Type: application/x-www-form-urlencoded
Accept: application/xml
Response:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <BookType xmlns="http://benchresources.in/cdm/Book"> <bookId>1</bookId> <bookName>Diagnostic Microbiology</bookName> <author>Patricia Tille</author> <category>Microbiology</category> </BookType>
2. Java client
Uses Client, ClientBuilder, WebTarget and Response classes from core JAX-RS package javax.ws.rs.client for invoking Restful web service
Note: Commented lines will help out us to try (set) various http request header parameters
TestBookService.java
package test.jersey.series.spring.hibernate.service; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.Invocation.Builder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.glassfish.jersey.client.ClientConfig; public class TestBookService { public static void main(String[] args) { // setting & invoking first service getBook/10001 System.out.println("Invoking and executing getBook service for book id 2"); String httpGetURL = "http://localhost:8080/Jersey-Spring-Hibernate/rest/bookservice/getbook/2"; String responseStringGet = testBookServiceForGetRequest(httpGetURL); System.out.println("GET >> Response String : " + responseStringGet); // setting & invoking second service addBook with XML request System.out.println("\n\nInvoking and executing addBook service with request XML"); String httpPostURL = "http://localhost:8080/Jersey-Spring-Hibernate/rest/bookservice/addbook"; String requestString = "{" + " \"bookId\": 6, " + " \"bookName\": \"Lange Microbiology and Infectious Diseases\"," + " \"author\": \"Kenneth D. Somers\"," + " \"category\": \"Microbiology\"" + "}"; String responseStringPost = testBookServiceForPostRequest(httpPostURL, requestString); System.out.println("POST >> Response String : " + responseStringPost); } /** * * @param httpURL * @return */ public static String testBookServiceForGetRequest(String httpURL){ // local variables ClientConfig clientConfig = null; Client client = null; WebTarget webTarget = null; Invocation.Builder invocationBuilder = null; Response response = null; int responseCode; String responseMessageFromServer = null; String responseString = null; try{ // invoke service after setting necessary parameters clientConfig = new ClientConfig(); client = ClientBuilder.newClient(clientConfig); // client.property("Content-Type", MediaType.APPLICATION_FORM_URLENCODED); // client.property("accept", MediaType.APPLICATION_XML); webTarget = client.target(httpURL); // invoke service invocationBuilder = webTarget.request(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_XML); // invocationBuilder.header("some-header", "header-value"); response = invocationBuilder.get(); // get response code responseCode = response.getStatus(); System.out.println("Response code: " + responseCode); if (response.getStatus() != 200) { throw new RuntimeException("Failed with HTTP error code : " + responseCode); } // get response message responseMessageFromServer = response.getStatusInfo().getReasonPhrase(); System.out.println("ResponseMessageFromServer: " + responseMessageFromServer); // get response string responseString = response.readEntity(String.class); } catch(Exception ex) { ex.printStackTrace(); } finally{ // release resources, if any response.close(); client.close(); } return responseString; } /** * * @param httpURL * @param requestString * @return */ public static String testBookServiceForPostRequest(String httpURL, String requestString) { // local variables ClientConfig clientConfig = null; Client client = null; WebTarget webTarget = null; Builder builder = null; Response response = null; int responseCode; String responseMessageFromServer = null; String responseString = null; try{ // invoke service after setting necessary parameters clientConfig = new ClientConfig(); client = ClientBuilder.newClient(clientConfig); // client.property("Content-Type", MediaType.APPLICATION_FORM_URLENCODED); // client.property("accept", MediaType.APPLICATION_JSON); webTarget = client.target(httpURL); // invoke service builder = webTarget.request(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON); response = builder.post(Entity.entity(requestString, MediaType.APPLICATION_JSON)); // get response code responseCode = response.getStatus(); System.out.println("Response code: " + responseCode); if (response.getStatus() != 200) { throw new RuntimeException("Failed with HTTP error code : " + responseCode); } // get response message responseMessageFromServer = response.getStatusInfo().getReasonPhrase(); System.out.println("ResponseMessageFromServer: " + responseMessageFromServer); // get response string responseString = response.readEntity(String.class); } catch(Exception ex) { ex.printStackTrace(); } finally{ // release resources, if any response.close(); client.close(); } return responseString; } }
Output in console
Invoking and executing getBook service for book id 2 Response code: 200 ResponseMessageFromServer: OK GET >> Response String : <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <BookType xmlns="http://benchresources.in/cdm/Book"> <bookId>2</bookId> <bookName>Microbiology Coloring Book</bookName> <author>I. Edward Alcamo</author> <category>Microbiology</category> </BookType> Invoking and executing addBook service with request XML Response code: 200 ResponseMessageFromServer: OK POST >> Response String : Book information saved successfully with Book_ID 6
Conclusion: Example went through in this article is almost an enterprise application with services exposed using Jersey 2.x JAX-RS web service and later integrating service/DAO layer with Hibernate (ORM) for database interaction
Download project
Jersey-2x-Spring-Hibernate (17kB)
Happy Coding !!
Happy Learning !!