Convert List Objects to/from JSON in Java Restful Web Services and Hibernate


Use JAR files which are listed below:

antlr-2.7.7.jar
asm-3.1.jar
commons-logging-1.1.3.jar
dom4j-1.6.1.jar
genson-1.3.jar
hibernate-commons-annotations-4.0.2.Final.jar
hibernate-core-4.2.5.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
jackson-core-asl-1.9.2.jar
jackson-jaxrs-1.9.2.jar
jackson-mapper-asl-1.9.2.jar
jackson-xc-1.9.2.jar
javassist-3.15.0-GA.jar
javax.servlet.jsp.jstl-1.2.2.jar
javax.servlet.jsp.jstl-api-1.2.1.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
jersey-client-1.18.jar
jersey-core-1.18.jar
jersey-json-1.19.3.jar
jersey-server-1.18.jar
jersey-servlet-1.18.jar
jettison-1.1.jar
jsr311-api-1.1.1.jar
mysql-connector-java-5.1.36.jar
taglibs-standard-impl-1.2.1.jar

Create a database with the name is learnjavarestfulwebservices. This database have a table: product table.

--
-- Table structure for table `product`
--

CREATE TABLE `product` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(250) NOT NULL,
  `price` decimal(10,1) NOT NULL,
  `quantity` int(11) NOT NULL,
  `status` tinyint(1) NOT NULL,
  `creationDate` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`name`, `price`, `quantity`, `status`, `creationDate`) VALUES('name 1', '12.2', 2, 1, '2017-12-28');
INSERT INTO `product` (`name`, `price`, `quantity`, `status`, `creationDate`) VALUES('name 2', '6.5', 6, 0, '2017-12-29');
INSERT INTO `product` (`name`, `price`, `quantity`, `status`, `creationDate`) VALUES('name 3', '11.8', 8, 1, '2017-12-18');

Structure of Product Table

Data of Product Table




Create 2 entities classes – Product.java and ProductEntity.java, to represent the above tables

Product.java

package entities;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@Table(name = "product")
@XmlRootElement(name = "product")
public class Product implements Serializable {


	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column
	private int id;
	private String name;
	private BigDecimal price;
	private int quantity;
	private boolean status;
	private Date creationDate;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	public boolean isStatus() {
		return status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}

	public Date getCreationDate() {
		return creationDate;
	}

	public void setCreationDate(Date creationDate) {
		this.creationDate = creationDate;
	}

}

ProductEntity.java

package entities;

import java.io.Serializable;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "productEntity")
public class ProductEntity implements Serializable {

	private int id;
	private String name;
	private BigDecimal price;
	private int quantity;
	private boolean status;
	private String creationDate;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	public boolean isStatus() {
		return status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}

	public String getCreationDate() {
		return creationDate;
	}

	public void setCreationDate(String creationDate) {
		this.creationDate = creationDate;
	}

}

Hibernate Configuration File

Puts Product.java in your Hibernate configuration file, and also MySQL connection details.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="hibernate.enable_lazy_load_no_trans">true</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/learnjavarestfulwebservices</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">123456</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="hibernate.current_session_context_class">thread</property>
		<mapping class="entities.Product" />
	</session-factory>
</hibernate-configuration>




The HibernateUtil class helps in creating the SessionFactory from the Hibernate configuration file. The SessionFactory is threadsafe, so it is not necessary to obtain one for each thread.

package models;

import org.hibernate.*;
import org.hibernate.boot.*;
import org.hibernate.boot.registry.*;

public class HibernateUtil {

	private static final SessionFactory sessionFactory;

	static {
		try {
			StandardServiceRegistry standardRegistry = new
					StandardServiceRegistryBuilder()
					.configure("hibernate.cfg.xml")
					.build();
			Metadata metaData = new MetadataSources(
					standardRegistry)
					.getMetadataBuilder()
					.build();
			sessionFactory = metaData.getSessionFactoryBuilder().build();
		} catch (Throwable th) {
			throw new ExceptionInInitializerError(th);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;

	}
}

The ProductModel class contains methods to interact with the database.

package models;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import entities.ProductEntity;

public class ProductModel {

	private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

	public List<ProductEntity> findAll() {
		List<ProductEntity> productEntities = null;
		Session session = null;
		Transaction transaction = null;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			Query query = session.createQuery("select p.id as id, "
												+ "p.name as name, "
												+ "p.price as price, "
												+ "p.quantity as quantity, "
												+ "p.status as status, "
												+ "DATE_FORMAT(p.creationDate, '%Y-%m-%d') as creationDate "
												+ "from Product p");
			productEntities = query.setResultTransformer(
								Transformers.aliasToBean(ProductEntity.class)
							  ).list();
			transaction.commit();
		} catch (Exception e) {
			productEntities = null;
			if (transaction != null) {
				transaction.rollback();
			}
		} finally {
			session.close();
		}
		return productEntities;
	}

}

Create Dynamic Web Project in Eclipse. Copy all jar files above to the lib directory in the project

This class is used to register a URL pattern in Jersey to intercept HTTP calls to the service. The marshaller, Jersey intercepts the path given in @ApplicationPath annotation such as – @ApplicationPath(“api”). This class extends javax.ws.rs.core.Application. All the RESTful web services and extensions needed are registered here.

ApplicationConfig.java

package ws;

import java.util.Set;
import javax.ws.rs.core.Application;

@javax.ws.rs.ApplicationPath("api")
public class ApplicationConfig extends Application {

	@Override
	public Set<Class<?>> getClasses() {
		Set<Class<?>> resources = new java.util.HashSet<>();
		addRestResourceClasses(resources);
		return resources;
	}

	private void addRestResourceClasses(Set<Class<?>> resources) {
		resources.add(controllers.ProductRestController.class);
	}

}




Create Restful Web Services provides application/json data for the client

package controllers;

import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import entities.ProductEntity;
import models.ProductModel;

@Path("product")
public class ProductRestController {

	@GET
	@Path("find_all")
	@Produces({ MediaType.APPLICATION_JSON })
	public Response findAll() {
		try {
			ProductModel productModel = new ProductModel();
			GenericEntity<List<ProductEntity>> genericEntity =
				new GenericEntity<List<ProductEntity>>(productModel.findAll()){};
			return Response.ok(genericEntity).build();
		} catch (Exception e) {
			return Response.status(Response.Status.BAD_REQUEST).build();
		}
	}

}

Access restful web services use the following url: http://localhost:8080/LearnJavaRestfulWebServices_Server/api/product/find_all

Output

[
	{"creationDate":"2017-12-28","id":1,"name":"name 1","price":12.2,"quantity":2,"status":true},
	{"creationDate":"2017-12-29","id":2,"name":"name 2","price":6.5,"quantity":6,"status":false},
	{"creationDate":"2017-12-18","id":3,"name":"name 3","price":11.8,"quantity":8,"status":true}
]

Create Java Project in Eclipse. Add all jar files above to the project

Create entities package in client project. Create a entity class: ProductEntity.java as below

ProductEntity.java

package entities;

import java.io.Serializable;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "productEntity")
public class ProductEntity implements Serializable {

	private int id;
	private String name;
	private BigDecimal price;
	private int quantity;
	private boolean status;
	private String creationDate;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	public boolean isStatus() {
		return status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}

	public String getCreationDate() {
		return creationDate;
	}

	public void setCreationDate(String creationDate) {
		this.creationDate = creationDate;
	}

}

DemoRestClientModel class contain methods call restful web services

package models;

import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class ProductRestClientModel {

	private String BASE_URL = "http://localhost:8080/LearnJavaRestfulWebServices_Server/api/";
	private WebResource webResource;
	private Client client;

	public ProductRestClientModel() {
		this.client = Client.create(new DefaultClientConfig());
		this.webResource = this.client.resource(BASE_URL).path("product");
	}

	public ClientResponse findAll() {
		ClientResponse response = null;
		try {
			WebResource resource = this.webResource;
			response = resource.path("find_all")
								.accept(MediaType.APPLICATION_JSON)
								.get(ClientResponse.class);
		} catch (Exception e) {
			response = null;
		}
		return response;
	}

}




package demo;

import java.util.List;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import entities.ProductEntity;
import models.ProductRestClientModel;

public class Main {

	public static void main(String[] args) {

		ProductRestClientModel productRestClientModel = new ProductRestClientModel();
		ClientResponse response = productRestClientModel.findAll();
		if(response != null) {
			int statusCode = response.getStatus();
			System.out.println("Response Status: " + statusCode);
			GenericType<List<ProductEntity>> genericEntity =
				new GenericType<List<ProductEntity>>(){};
			List<ProductEntity> productEntities = response.getEntity(genericEntity);
			System.out.println("\nProduct List");
			for(ProductEntity productEntity : productEntities) {
				System.out.println("Id: " + productEntity.getId());
				System.out.println("Name: " + productEntity.getName());
				System.out.println("Price: " + productEntity.getPrice());
				System.out.println("Quantity: " + productEntity.getQuantity());
				System.out.println("Status: " + productEntity.isStatus());
				System.out.println("Creation Date: " + productEntity.getCreationDate());
				System.out.println("=========================");
			}
		} else {
			System.err.println("Can not access find_all web method");
		}

	}

}
Response Status: 200

Product List
Id: 1
Name: name 1
Price: 12.2
Quantity: 2
Status: true
Creation Date: 2017-12-28
=========================
Id: 2
Name: name 2
Price: 6.5
Quantity: 6
Status: false
Creation Date: 2017-12-29
=========================
Id: 3
Name: name 3
Price: 11.8
Quantity: 8
Status: true
Creation Date: 2017-12-18
=========================