Tuesday, May 3, 2016

Spring Restful Web Service With Hibernate ORM in GET and POST

Download Complete Project
Steps
  1. Click File-> New-> Maven Project
  2. Select your work space .

  1. Select “maven arcehtype webapp”
  2. Give GroupId and Artifact Id

  1. Now Right Click on Project go to Properties And Select Target Runtime and Add new Server
  2. Click Finish and Apply
  3. Now Add below code in Web.xml
<servlet>  
<servlet-name>springrest</servlet-name>  
<servlet-class>  
 org.springframework.web.servlet.DispatcherServlet  
</servlet-class>  
<load-on-startup>1</load-on-startup>  
</servlet>  
 
<servlet-mapping>  
<servlet-name>springrest</servlet-name>  
<url-pattern>/</url-pattern>  
</servlet-mapping>

13.Add below code in pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringRestService</groupId>
<artifactId>BMI</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>BMI Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>

<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>


<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.4.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>



</dependencies>
<build>
<finalName>SpringRestService</finalName>

<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
</plugins>

</build>
<properties>
<spring.version>4.2.5.RELEASE</spring.version>
<jdk.version>1.7</jdk.version>
</properties>
</project>


14.Now Update Maven Project it will download libraries mention in pom.xml
15. Now Create new xml File “springrest-servlet.xml” Under “WEB-INF” folder

16.Now Copy below code in above xml file
<beans xmlns="http://www.springframework.org/schema/beans"  
xmlns:context="http://www.springframework.org/schema/context"  
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context   
       http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
 
<mvc:annotation-driven/>  
<context:component-scan base-package="myRestBean.controller" />  
 
</beans>  
17. In above xml file highlighted part should be change according to your “Controller.java” bean file
18. Now Open below highlighted path in Windows Explorer. And Create new Folder “java” so that folder srtucture becomes “E:\Spring Rest Service\BMI\src\main\java” and Right click on project and select Refresh
19. Now Right Click on “src/main/java” Create new Class The bellow package
20.Copy Below code to Class File
package myRestBean.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import javax.servlet.http.HttpServletResponse;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ResponseBody;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import com.fasterxml.jackson.databind.util.Converter;



@RestController
@RequestMapping("/hello")
public class SpringController {

private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
//@Autowired
//PersonaldetailsService personaldetailsService;

/*
* @RequestMapping(value = "/{name}", method = RequestMethod.GET) public
* String getGreeting(@PathVariable String name) { String
* result="Hello "+name; return result; }
*/
//http://localhost:8080/SpringRestService/hello/greeting?name=ambadnya
@RequestMapping(value = "/greeting", method = RequestMethod.GET, headers = "Accept=application/json")
public Greeting greeting(
@RequestParam(value = "name", defaultValue = "World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template,
name));

}

//http://localhost:8080/SpringRestService/hello/country/2
@RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public Country getCountryById(@PathVariable int id) {
List<Country> listOfCountries = new ArrayList<Country>();
listOfCountries = createCountryList();

for (Country country : listOfCountries) {
if (country.getId() == id)
return country;
}
return null;
}

@RequestMapping(value = "/personaldetails/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public Personaldetails getPerson(@PathVariable int id) throws IOException {
List<Personaldetails> listOfCountries = new ArrayList<Personaldetails>();
listOfCountries = listEmployees(id);

for (Personaldetails country : listOfCountries) {
return country;
}
return null;
}
//http://localhost:8080/SpringRestService/hello/updateperson/2?name=amits
@RequestMapping(value = "/updateperson/{id}", method = RequestMethod.GET, headers = "Accept=application/text")
public String UpdatePerson(@PathVariable int id,@RequestParam(value = "name", defaultValue = "World") String name) throws IOException {
//List<Personaldetails> listOfCountries = new ArrayList<Personaldetails>();
//listOfCountries = listEmployees(id);
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()). buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session =  sessionFactory.openSession();
     Transaction tx = null;
     try{
        tx = session.beginTransaction();
        Personaldetails employee = (Personaldetails)(session).get(Personaldetails.class, id);
        employee.setF_name(name);
session.update(employee);
        tx.commit();
     }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
        return "fail";
     }finally {
        session.close();
     }
return "success";
}
//http://localhost:8080/SpringRestService/hello/insertpersonal?pid=4&fname=amits&mname=amits&lname=amits&addrs=amits&age=50&gender=male
@RequestMapping(value = "/insertpersonal", method = RequestMethod.GET, headers = "Accept=application/json")
public String insertPerson(/*@RequestParam(value = "pid")int pid,
@RequestParam(value = "fname")String fname,
@RequestParam(value = "mname")String mname,
@RequestParam(value = "lname")String lname,
@RequestParam(value = "addrs")String addrs,
@RequestParam(value = "age")int age,
@RequestParam(value = "gender")String gender*/@RequestParam Map<String, String> requestParams,HttpServletResponse resp) throws IOException {
String strpid = requestParams.get( "pid" );
String fname = requestParams.get ( "fname" );
String mname = requestParams.get ( "mname" );
String lname = requestParams.get ( "lname" );
String addrs = requestParams.get ( "addrs" );
String strage = requestParams. get( "age" );
String gender = requestParams. get( "gender" );
int pid =  Integer.parseInt(strpid);
int age =  Integer.parseInt(strage);
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()). buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session =  sessionFactory.openSession();
Transaction tx = null;
     try{
tx = session.beginTransaction();
Personaldetails pers= new Personaldetails(pid, fname, mname, lname, addrs, age, gender);
session.save(pers);
tx.commit();
     }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
        return "{\"status\":\"fail\"}";
     }finally {
        session.close();
     }
     resp.setContentType( "application/json" );
     resp.setStatus(200);
     return "{\"status\":\"success\"}";
}
//http://localhost:8080/SpringRestService/hello/insertpersonalpost
//Content
/*{
"pid": "7",
"f_name": "amits",
"m_name": "shridhar",
"l_name": "salvi",
"address": "gorai",
"age": "50",
"gender": "male"
}*/
@RequestMapping(value = "/insertpersonalpost", method = RequestMethod.POST, headers = "Accept=application/json")
public String insertPersonPost(@RequestBody Personaldetails requestBody,HttpServletResponse resp) throws IOException {
int pid = requestBody.getPid();
String fname = requestBody.getF_name();
String mname = requestBody.getM_name();
String lname = requestBody.getL_name();
String addrs = requestBody.getAddress();
int age = requestBody.getAge();
String gender = requestBody.getGender();
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()). buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session =  sessionFactory.openSession();
Transaction tx = null;
     try{
tx = session.beginTransaction();
Personaldetails pers= new Personaldetails(pid, fname, mname, lname, addrs, age, gender);
session.save(pers);
tx.commit();
     }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
        return "{\"status\":\"fail\"}";
     }finally {
        session.close();
     }
     resp.setContentType( "application/json" );
     resp.setStatus(200);
     return "{\"status\":\"success\"}";
}

public List<Country> createCountryList() {
Country indiaCountry = new Country(1, "India");
Country chinaCountry = new Country(4, "China");
Country nepalCountry = new Country(3, "Nepal");
Country bhutanCountry = new Country(2, "Bhutan");

List<Country> listOfCountries = new ArrayList<Country>();
listOfCountries.add(indiaCountry);
listOfCountries.add(chinaCountry);
listOfCountries.add(nepalCountry);
listOfCountries.add(bhutanCountry);
return listOfCountries;
}
public List<Personaldetails> listEmployees(int id) throws IOException{
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()). buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session =  sessionFactory.openSession();
List<Personaldetails> employees = null;
     Transaction tx = null;
     try{
        tx = session.beginTransaction();
         employees = session.createQuery("FROM Personaldetails where pid="+id).list(); //table name should be class name
        for (Iterator iterator = employees.iterator(); iterator.hasNext();){
           Personaldetails employee = (Personaldetails) iterator.next();
           System.out.print("First Name: " + employee.getF_name());
           System.out.print("  Last Name: " + employee.getL_name());
           System.out.println("  Salary: " + employee.getAge());
        }
        tx.commit();
     }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
     }finally {
        session.close();
     }
  return employees;
  }


}


21 Now Create “hibernate.cfg.xml” as show below and add below code in the file
This file contains Database connection details here it is MySql Connection.
restful1.jpg
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/employee_mgmt</property>
<property name="hibernate.connection.username">amit</property>
<property name="hibernate.connection.password">amit</property>
<!-- List of XML mapping files -->
<mapping resource="Personaldetails.hbm.xml" />
</session-factory>
</hibernate-configuration>

In Above file highlighted part is a file which contains the Table related Details.

22. Now create that file "Personaldetails.hbm.xml" in same folder as shown in above image and add below code.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="myRestBean.controller.Personaldetails" table="personaldetails1">
     <meta attribute="class-description">
        This class contains the employee detail.
     </meta>
     <id name="pid" type="int" column="pid">
        
     </id>
     <property name="f_name" column="f_name" type="string"/>
     <property name="l_name" column="l_name" type="string"/>
     <property name="m_name" column="m_name" type="string"/>
     <property name="address" column="address" type="string"/>
     <property name="age" column="age" type="int"/>
     <property name="gender" column="gender" type="string"/>
  </class>
</hibernate-mapping>

In Above file yellow highlighted part is the name of Personaldetails.java which contains getters and setter for respective table column.
Where as blue highlighted is table name in DataBase  
Where as purpule highlighted are columns in that table where pid is primary key.  



23 below is the Personaldetails.java file
package myRestBean.controller;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

public class Personaldetails {

private int pid;
private String f_name;
private String m_name;
private String l_name;
private String address;
private int age;
private String gender;
public Personaldetails()
{}
public Personaldetails(int pid,String f_name,String m_name,String l_name,String address , int age,String gender ) {
this.pid = pid;
this.f_name = f_name;
this.m_name = m_name;
this.l_name = l_name;
this.address = address;
this.age = age;
this.gender = gender;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
public String getM_name() {
return m_name;
}
public void setM_name(String m_name) {
this.m_name = m_name;
}
public String getL_name() {
return l_name;
}
public void setL_name(String l_name) {
this.l_name = l_name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}



24. Now Again Update the Maven Project

25 Below is Post Response

No comments:

Post a Comment