Create Operator 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.text.SimpleDateFormat;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import entities.Product;
import entities.ProductEntity;

public class ProductModel {

	private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

	public boolean create(ProductEntity productEntity) {
		boolean result = true;
		Session session = null;
		Transaction transaction = null;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			Product product = new Product();
			product.setName(productEntity.getName());
			product.setPrice(productEntity.getPrice());
			product.setQuantity(productEntity.getQuantity());
			product.setStatus(productEntity.isStatus());
			product.setCreationDate(simpleDateFormat.parse(productEntity.getCreationDate()));
			session.save(product);
			transaction.commit();
		} catch (Exception e) {
			result = false;
			if (transaction != null) {
				transaction.rollback();
			}
		} finally {
			session.close();
		}
		return result;
	}

}

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 javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import entities.ProductEntity;
import models.ProductModel;

@Path("product")
public class ProductRestController {

	@POST
	@Path("create")
	@Consumes({ MediaType.APPLICATION_JSON })
	public Response create(ProductEntity productEntity) {
		try {
			ProductModel productModel = new ProductModel();
			boolean result = productModel.create(productEntity);
			return Response.ok(String.valueOf(result)).build();
		} catch (Exception e) {
			return Response.status(Response.Status.BAD_REQUEST).build();
		}
	}

}

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;

import entities.ProductEntity;

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 create(ProductEntity productEntity) {
		ClientResponse response = null;
		try {
			WebResource resource = this.webResource;
			response = resource.path("create")
								.accept(MediaType.APPLICATION_JSON)
								.post(ClientResponse.class, productEntity);
		} catch (Exception e) {
			response = null;
		}
		return response;
	}

}




package demo;

import java.math.BigDecimal;
import com.sun.jersey.api.client.ClientResponse;
import entities.ProductEntity;
import models.ProductRestClientModel;

public class Main {

	public static void main(String[] args) {

		ProductRestClientModel productRestClientModel = new ProductRestClientModel();
		ProductEntity productEntity = new ProductEntity();
		productEntity.setName("name 4");
		productEntity.setPrice(BigDecimal.valueOf(123));
		productEntity.setQuantity(4);
		productEntity.setStatus(true);
		productEntity.setCreationDate("2017-12-29");
		ClientResponse response = productRestClientModel.create(productEntity);
		if (response != null) {
			int statusCode = response.getStatus();
			System.out.println("Response Status: " + statusCode);
			boolean result = response.getEntity(Boolean.class);
			System.out.println("Result: " + result);
		} else {
			System.err.println("Can not access create web method");
		}

	}

}
Response Status: 200
Result: true