Spring boot

Spring boot crud example with hibernate mysql

Spring boot allows the developer to integrate hibernate classic way of implementation by adding hibernate configuration to spring boot application, If you are using older application or you need full control of hibernate implementation, you can follow this approach to build the application.

Spring boot Starter (pom.xml)

There is no special starter needed for hibernate, spring boot data jpa will do all the magic.

	4.0.0
	com.candidjava.spring.boot
	helloworld
	0.0.1-SNAPSHOT
	helloworld-rest-hib-curd
	http://maven.apache.org
	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.4.RELEASE
	
	
		UTF-8
		1.8
	
	
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.springframework.boot
			spring-boot-starter-data-jpa
		
		
			mysql
			mysql-connector-java
		
		
		
			org.springframework.boot
			spring-boot-starter-tomcat
			provided
		
		
			org.springframework.boot
			spring-boot-devtools
true
		
	
	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
		Spring-Boot-Restfull
	

Hibernate Configuration

Load your hibernate configuration into spring boot using @Configuration annotation and keep all your properties in application.properties file.

application.properties

logging.level.org.springframework.web=DEBUG
# Database
db.driver: com.mysql.jdbc.Driver
db.url: jdbc:mysql://localhost:3306/test
db.username: root
db.password: root

# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: update
entitymanager.packagesToScan: com

HibernateConfiguration.java

package com.candidjava.spring.configuration;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class HibernateConfiguration {

 @Value("${db.driver}")
 private String DB_DRIVER;

 @Value("${db.password}")
 private String DB_PASSWORD;

 @Value("${db.url}")
 private String DB_URL;

 @Value("${db.username}")
 private String DB_USERNAME;

 @Value("${hibernate.dialect}")
 private String HIBERNATE_DIALECT;

 @Value("${hibernate.show_sql}")
 private String HIBERNATE_SHOW_SQL;

 @Value("${hibernate.hbm2ddl.auto}")
 private String HIBERNATE_HBM2DDL_AUTO;

 @Value("${entitymanager.packagesToScan}")
 private String ENTITYMANAGER_PACKAGES_TO_SCAN;

 @Bean
 public LocalSessionFactoryBean sessionFactory() {
  LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

  sessionFactory.setDataSource(dataSource());

  sessionFactory.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);

  Properties hibernateProperties = new Properties();
  hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
  hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
  hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
  sessionFactory.setHibernateProperties(hibernateProperties);

  return sessionFactory;
 }

 @Bean
 public DataSource dataSource() {
  DriverManagerDataSource dataSource = new DriverManagerDataSource();
  dataSource.setDriverClassName(DB_DRIVER);
  dataSource.setUrl(DB_URL);
  dataSource.setUsername(DB_USERNAME);
  dataSource.setPassword(DB_PASSWORD);
  return dataSource;
 }

 @Bean
 public HibernateTransactionManager transactionManager() {
  HibernateTransactionManager txManager = new HibernateTransactionManager();
  txManager.setSessionFactory(sessionFactory().getObject());
  return txManager;
 }

}

Hibernate Implementation

The below is the old hibernate classic code, I have just copied and pasted init.

UserDao.java

package com.candidjava.spring.dao;

import java.util.List;

import com.candidjava.spring.bean.User;

public interface UserDao {
 public void addUser(User user);
 public List<User> getUser();
 public User findById(int id);
 public User update(User user, int id);
 public User updateCountry(User user, int id);
 public void delete(int id);
}

UserDaoImp.java

package com.candidjava.spring.dao;

import java.util.List;

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

import com.candidjava.spring.bean.User;
@Repository
public class UserDaoImp implements UserDao {
 @Autowired
 private SessionFactory sessionFactory;

 public void addUser(User user) {
  // TODO Auto-generated method stub
  Session session = sessionFactory.getCurrentSession();
  session.save(user);
 }

 public List<User> getUser() {
  // TODO Auto-generated method stub
  Session session = sessionFactory.getCurrentSession();
  @SuppressWarnings("unchecked")
  List<User> list = session.createCriteria(User.class).list();
  return list;
 }

 public User findById(int id) {
  // TODO Auto-generated method stub
  Session session = sessionFactory.getCurrentSession();
  User user = (User) session.get(User.class, id);
  return user;
 }

 public User update(User val, int id) {
  // TODO Auto-generated method stub
  Session session = sessionFactory.getCurrentSession();
  User user = (User) session.get(User.class, id);
  user.setCountry(val.getCountry());
  user.setName(val.getName());
  session.update(user);
  return user;
 }

 public void delete(int id) {
  // TODO Auto-generated method stub
  Session session = sessionFactory.getCurrentSession();
  User user = findById(id);
  session.delete(user);
 }
 @Override
 public User updateCountry(User val, int id) {
  Session session = sessionFactory.getCurrentSession();
  User user = (User) session.load(User.class, id);
  user.setCountry(val.getCountry());
  return user;
 }

}

UserController.java

package com.candidjava.spring.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.service.UserService;

@RestController
@RequestMapping(value = {
 "/user"
})
public class UserController {
 @Autowired
 UserService userService;

 @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
 public ResponseEntity<User> getUserById(@PathVariable("id") int id) {
  System.out.println("Fetching User with id " + id);
  User user = userService.findById(id);
  if (user == null) {
   return new ResponseEntity<User> (HttpStatus.NOT_FOUND);
  }
  return new ResponseEntity<User> (user, HttpStatus.OK);
 }

 @PostMapping(value = "/create", headers = "Accept=application/json")
 public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
  System.out.println("Creating User " + user.getName());
  userService.createUser(user);
  HttpHeaders headers = new HttpHeaders();
  headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
  return new ResponseEntity<Void> (headers, HttpStatus.CREATED);
 }

 @GetMapping(value = "/get", headers = "Accept=application/json")
 public List<User> getAllUser() {
  List<User> tasks = userService.getUser();
  return tasks;

 }

 @PutMapping(value = "/update", headers = "Accept=application/json")
 public ResponseEntity<String> updateUser(@RequestBody User currentUser) {
  System.out.println("sd");
  User user = userService.findById(currentUser.getId());
  if (user == null) {
   return new ResponseEntity<String> (HttpStatus.NOT_FOUND);
  }
  userService.update(currentUser, currentUser.getId());
  return new ResponseEntity<String> (HttpStatus.OK);
 }

 @DeleteMapping(value = "/{id}", headers = "Accept=application/json")
 public ResponseEntity<User> deleteUser(@PathVariable("id") int id) {
  User user = userService.findById(id);
  if (user == null) {
   return new ResponseEntity<User> (HttpStatus.NOT_FOUND);
  }
  userService.deleteUserById(id);
  return new ResponseEntity<User> (HttpStatus.NO_CONTENT);
 }

 @PatchMapping(value = "/{id}", headers = "Accept=application/json")
 public ResponseEntity<User> updateUserPartially(@PathVariable("id") int id, @RequestBody User currentUser) {
  User user = userService.findById(id);
  if (user == null) {
   return new ResponseEntity<User> (HttpStatus.NOT_FOUND);
  }
  User usr = userService.updatePartially(currentUser, id);
  return new ResponseEntity<User> (usr, HttpStatus.OK);
 }
}

UserService.java

package com.candidjava.spring.service;

import java.util.List;

import com.candidjava.spring.bean.User;

public interface UserService {
 public void createUser(User user);
 public List<User> getUser();
 public User findById(int id);
 public User update(User user, int id);
 public void deleteUserById(int id);
 public User updatePartially(User user, int id);
}

UserServiceImp.java

package com.candidjava.spring.service;

import java.util.List;

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

import com.candidjava.spring.bean.User;
import com.candidjava.spring.dao.UserDao;

@Service
@Transactional
public class UserServiceImp implements UserService {
 @Autowired
 UserDao userDao;


 public List<User> getUser() {
  // TODO Auto-generated method stub
  return userDao.getUser();
 }

 public User findById(int id) {
  // TODO Auto-generated method stub
  return userDao.findById(id);
 }

 public void createUser(User user) {
  // TODO Auto-generated method stub
  userDao.addUser(user);
 }

 public void deleteUserById(int id) {
  // TODO Auto-generated method stub
  userDao.delete(id);
 }
 @Override
 public User updatePartially(User user, int id) {
  userDao.updateCountry(user, id);
  return userDao.findById(id);
 }

 @Override
 public User update(User user, int id) {
  // TODO Auto-generated method stub
  return userDao.update(user, id);
 }

}

User.java

package com.candidjava.spring.bean;

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 com.fasterxml.jackson.annotation.JsonIgnoreProperties;


@Entity
@Table(name = "UserInfo")
@JsonIgnoreProperties({
 "hibernateLazyInitializer",
 "handler"
})
public class User {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private int id;

 @Column(name = "country")
 private String country;
 @Column(name = "name")

 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;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

}

Launch as Spring boot (Application.java)

package com.candidjava;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
public class Application {
 public static void main(String[] args) {
  SpringApplication.run(Application.class, args);
 }

}

Download

Download source code from my github account Click here