Overview

In this tutorial, we show you how to create a Hibernate CRUD Restful WebService using Spring MVC 4 and Mysql Database

Building Hibernate CRUD Restful WebService using Spring MVC 4


Video Tutorials




Follow the steps mentioned below to develop this application.

Create Database


CREATE DATABASE `springrestful`;

Create Database Table


 CREATE TABLE  `user` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `name` varchar(45) NOT NULL DEFAULT '',

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;


Project Structure


Spring Restful Webservice CRUD Project Structure

Create Maven Project

  • Launch Eclipse IDE.
  • Go to File-> New-> Others... Select Maven Project under Maven category then click Next.
  • In New Maven Project wizard, select "Create a simpel project(skip archetype selection)" and click on Next
  • In next wizard, type "springmvc_example" in the "Group ID:" field
  • Type "SpringRestfulWebserviceHibernate" in the "Artifact Id:" field
  • Packaging -> War
  • Click Finish.

Update pom.xml to include required dependencies

Open pom.xml file and add the following dependencies in it.



Configure WebApp and Hibernate

  • Right click to the src folder, select New -> Package
  • Enter "springmvc_example.config" in Name: field
  • Click Finish

Create a WebConfig class under springmvc_example.config package and write the following code in it

package springmvc_example.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan({"springmvc_example"})
public class WebConfig {

}

Create a WebInitializer class under springmvc_example.config package and write the following code in it

package springmvc_example.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

 @Override
 protected Class[] getRootConfigClasses() {
  return new Class[]{ WebConfig.class };
 }

 @Override
 protected Class[] getServletConfigClasses() {
  return null;
 }

 @Override
 protected String[] getServletMappings() {
  return new String[]{ "/" };
 }

}

Configure Hibernate


Create a HibernateConfig class under springmvc_example.config package and write the following code in it

package springmvc_example.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScan({ "springmvc_example.config" })
public class HibernateConfig {
 
 @Bean
 public LocalSessionFactoryBean sessionFactoryBean(){
  LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
  sessionFactoryBean.setDataSource(dataSource());
  sessionFactoryBean.setPackagesToScan(new String[] { "springmvc_example.model" });
  sessionFactoryBean.setHibernateProperties(hibernateProperties());
  
  return sessionFactoryBean;
 }
 
 @Bean
 public DataSource dataSource(){
  DriverManagerDataSource ds = new DriverManagerDataSource();
  ds.setDriverClassName("com.mysql.jdbc.Driver");
  ds.setUrl("jdbc:mysql://localhost:3306/springrestful");
  ds.setUsername("root");
  ds.setPassword("root");
  
  return ds;
 }
 
 private Properties hibernateProperties(){
  Properties properties = new Properties();
  properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
  properties.put("hibernate.show_sql", "true");
  properties.put("hibernate.format_sql", "false");
  
  return properties;
 }
 
 @Bean
 @Autowired
 public HibernateTransactionManager transactionManager(SessionFactory s){
  HibernateTransactionManager txManager = new HibernateTransactionManager();
  txManager.setSessionFactory(s);
  
  return txManager;
 }
 
}

MySQL Database Name: springrestful
Password for MySQL: root
Username for MySQL: root

Creating Persistence Layer

Create a User class under springmvc_example.model package and write the following code in it

package springmvc_example.model;

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

@Entity
@Table(name="user")
public class User {

 @Id
 @GeneratedValue(strategy= GenerationType.IDENTITY)
 private int id;
 
 @Column(name="name", nullable=true)
 private String name;
 
 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;
 }

}

Creating DAO Layer

Create a UserDao Interface under springmvc_example.dao package and write the following code in it

package springmvc_example.dao;

import java.util.List;

import springmvc_example.model.User;

public interface UserDao {
 
 public List getListUser();
 
 public void saveOrUpdate(User user);
 
 public void deleteUser(int id);
 
 public User findUserById(int id);
 
}

Create a UserDaoImpl class implements UserDao Interface under springmvc_example.dao package and write the following code in it

package springmvc_example.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import springmvc_example.model.User;

@Repository
public class UserDaoImpl implements UserDao {
 
 @Autowired
 private SessionFactory sessionFactory;
 
 protected Session getSession(){
  return sessionFactory.getCurrentSession();
 }

 @SuppressWarnings("unchecked")
 public List getListUser() {
  Criteria criteria = getSession().createCriteria(User.class);
  
  return (List) criteria.list();
 }

 public void saveOrUpdate(User user) {
  getSession().saveOrUpdate(user);
 }

 public void deleteUser(int id) {
  User user = (User) getSession().get(User.class, id);
  getSession().delete(user);
 }

 public User findUserById(int id) {
  return (User) getSession().get(User.class, id);
 }

}

Creating Service Layer

Create a UserService Interface under package springmvc_example.service package and write the following code in it

package springmvc_example.service;

import java.util.List;

import springmvc_example.model.User;

public interface UserService {
 
 public List getListUser();
 
 public void saveOrUpdate(User user);
 
 public void deleteUser(int id);
 
 public User findUserById(int id);
 
}

Create a UserServiceImpl class implements UserService Interface under springmvc_example.service package and write the following code in it 

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import springmvc_example.dao.UserDao;
import springmvc_example.model.User;

@Service
@Transactional
public class UserServiceImpl implements UserService {
 
 UserDao userDao;
 
 @Autowired
 public void setUserDao(UserDao userDao) {
  this.userDao = userDao;
 }

 public List getListUser() {
  return userDao.getListUser();
 }

 public void saveOrUpdate(User user) {
  userDao.saveOrUpdate(user);
 }

 public void deleteUser(int id) {
  userDao.deleteUser(id);
 }

 public User findUserById(int id) {
  return userDao.findUserById(id);
 }

}

Creating Controller Layer

Create a UserController class under package springmvc_example.controller package and write the following code in it 

package springmvc_example.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import springmvc_example.model.User;
import springmvc_example.service.UserService;

@RestController
public class UserController {

 @Autowired
 UserService userService;
 
 @RequestMapping(value="/user/", method=RequestMethod.GET, headers="Accept=application/json")
 public @ResponseBody List getListUser(){
  List users = userService.getListUser();
  
  return users;
 }
 
 @RequestMapping(value="/add/", method=RequestMethod.POST)
 public @ResponseBody User add(@RequestBody User user){
  userService.saveOrUpdate(user);
  
  return user;
 }
 
 @RequestMapping(value="/update/{id}", method=RequestMethod.PUT)
 public @ResponseBody User update(@PathVariable("id") int id, @RequestBody User user){
  user.setId(id);
  userService.saveOrUpdate(user);
  
  return user;
 }
 
 @RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE)
 public @ResponseBody User delete(@PathVariable("id") int id){
  User user = userService.findUserById(id);
  userService.deleteUser(id);
  
  return user;
 }
 
}


Building

  • Right click this project
  • Select Run As -> Maven clean
  • Right click this project
  • Select Run As -> Maven install

Configuring Apache Tomcat

  • Under Servers tab, click link "No servers are available. Click this link to create a new server ...", select Apache tomcat 7
  • Click Finish

configuration apache tomcat eclipse

configuration apache tomcat 7 eclipse


  • Right click "Tomcat v7.0 Server at localhost [Stopped, Republish]", select "Add and Remove ..."
  • Add SpringRestfulWebServiceHibernate project, then Click Finish
  • Open server.xml file under Servers Folder
  • Find line

<Context docBase="SpringRestfulWebServiceHibernate" path="/SpringRestfulWebServiceHibernate" reloadable="true" source="org.eclipse.jst.jee.server:SpringRestfulWebServiceHibernate" />
 
Update its as below: 

<Context docBase="<Project Folder Location>\SpringRestfulWebServiceHibernate\SpringRestfulWebServiceHibernate\target\SpringRestfulWebServiceHibernate-0.0.1-SNAPSHOT\" path="/SpringRestfulWebServiceHibernate" reloadable="true" />

  • Copy mysql-connector-java-5.1.45-bin.jar file to <Apache Tomcat Folder Location>\apache-tomcat-7.0.68\lib\

Watch video add Apache Tomcat Server in Eclipse IDE



Run & Check result

  • Start Apache Tomcat from Eclipse IDE.
  • Open Postman tool (Postman is the complete toolchain for API developers)

Add User API

Request Method: POST
URL: http://localhost:8080/SpringRestfulWebServiceHibernate/add/
Body: Type application/json
{
 "name": "Test1"
}

run postman add user


Update User API
Request Method: PUT
URL: http://localhost:8080/SpringRestfulWebServiceHibernate/update/1
Body: Type application/json
{
 "name": "Test1 Updated"
}

run postman update user


Get User API
Request Method: GET
URL: http://localhost:8080/SpringRestfulWebServiceHibernate/user/

run postman get user



Delete User API
Request Method: DELETE
URL: http://localhost:8080/SpringRestfulWebServiceHibernate/delete/1

run postman delete user

Required Libraries



Previous Post
Next Post

post written by: