Saturday 18 August 2018

Spring Boot & Hibernate With Spring Data JPA(Traditional Approach)

Spring Data-JPA With Hibernate



As we know that, JPA is a specification whereas Hibernate is a specific implementation of that specification. If we are using Hibernate it means we are tightly coupling our code with specific providers which restricts us to freely move towards different approach or implementation if required in future.

Spring Data JPA adds a layer of abstraction means it defines a standard or generic design to support persistence layer in Spring context. So, Spring Data JPA provides a definition to implement repositories that are referenced by JPA specification using the provider which we mention. Spring-data-JPA is the spring way to access data using JPA. We could use spring-data-rest on top of spring-data-JPA to create a REST-API layer with no code on top of your repositories and entities.



We will see below an example of hibernate with traditional approach using spring boot.

Use https://start.spring.io/  to create spring boot project with adding web and Spring-data-JPA dependency. I have also added mysql connector dependency.


1) 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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gaurav</groupId>
<artifactId>springboot-hibernate-Spring-Data-JPA</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<properties>
<java.version>1.8</java.version>
</properties>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>

</project>

2) Employee.java

package com.gaurav.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
 * @author Gaurav
 */
@Entity
@Table(name="employee")
public class Employee {

@Id
@Column
@GeneratedValue
private int id;

@Column
private String firstName;
@Column
private String lastName;
@Column
private String email;
@Column
private String designation;

public int getId() {
return id;
}

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

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getDesignation() {
return designation;
}

public void setDesignation(String designation) {
this.designation = designation;
}
}


3. EmployeeDao.java

package com.gaurav.dao;

import java.util.List;

import com.gaurav.model.Employee;
/**
 * @author Gaurav
 */
public interface EmployeeDao {
public List<Employee> getAllEmployeeDetails();
public Employee getEmployeeById(int id);
public int saveEmployee(Employee emp);

}

4. EmployeeDaoImpl.java

package com.gaurav.dao.impl;

import java.util.List;

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

import com.gaurav.dao.EmployeeDao;
import com.gaurav.model.Employee;
/**
 * @author Gaurav
 */
@Repository
public class EmployeeDaoImpl implements EmployeeDao {

@Autowired
private SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
public List<Employee> getAllEmployeeDetails() {
Criteria criteria = sessionFactory.openSession().createCriteria(Employee.class);
return criteria.list();
}
@SuppressWarnings("unchecked")
public Employee getEmployeeById(int id){
Employee employee = null;
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Criteria criteria = session.createCriteria(Employee.class);
List<Employee> employeeList = criteria.add(Restrictions.eq("id", new Integer(id))).list();
if(!employeeList.isEmpty())
employee = employeeList.get(0);
tx.commit();
session.close();
return employee;
}
public int saveEmployee(Employee emp){
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Integer i = (Integer)session.save(emp);
System.out.println("Generated Identifier while saving the employee object:"+ i);
tx.commit();
session.close();
return i;
}
}

5. EmployeeService.java

package com.gaurav.service;

import java.util.List;

import com.gaurav.model.Employee;
/**
 * @author Gaurav
 */
public interface EmployeeService {

List<Employee> getAllEmployeeDetails();
public Employee getEmpById(int id);
public int saveEmployee(Employee emp);

}

6. EmployeeServiceImpl.java

package com.gaurav.service.impl;

import java.util.List;

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

import com.gaurav.dao.EmployeeDao;
import com.gaurav.model.Employee;
import com.gaurav.service.EmployeeService;
/**
 * @author Gaurav
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

@Autowired
private EmployeeDao employeeDao;

public List<Employee> getAllEmployeeDetails() {
return employeeDao.getAllEmployeeDetails();

}

public Employee getEmpById(int id){
return employeeDao.getEmployeeById(id);
}

public int saveEmployee(Employee emp){
return employeeDao.saveEmployee(emp);
}
}

7. EmployeeController.java

package com.gaurav.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
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.RestController;

import com.gaurav.model.Employee;
import com.gaurav.service.EmployeeService;

@RestController
@RequestMapping("/rest")
public class EmployeeController {
@Autowired
private EmployeeService empService;
@RequestMapping(value = "/allemps", method = RequestMethod.GET)
public ResponseEntity<List<Employee>> allEmployeeDetails() {
        
List<Employee> empDetails = empService.getAllEmployeeDetails();
return new ResponseEntity<List<Employee>>(empDetails, HttpStatus.OK);
}
@GetMapping(value = "/emp/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable int id){
Employee employee = empService.getEmpById(id);
return new ResponseEntity<Employee>(employee, HttpStatus.OK);
}
@PostMapping(value = "/save")
public ResponseEntity<Integer> saveEmployee(@RequestBody Employee emp){
Integer id = empService.saveEmployee(emp);
return new ResponseEntity<Integer>(id, HttpStatus.OK);
}
}

8. SpringBootHibernateDemo.java

package com.gaurav;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootHibernateDemo {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootHibernateDemo.class, args);
    }

}

9. application.properties

server.port=8989
spring.datasource.url = jdbc:mysql://localhost:3306/experiment
spring.datasource.username = root
spring.datasource.password = root

spring.jpa.show-sql = true

spring.jpa.hibernate.ddl-auto = update

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

10. HibernateBeanConfiguration.java

package com.gaurav.hibernate.util;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.persistence.EntityManagerFactory;


@Configuration
public class HibernateBeanConfiguration {

@Autowired
private EntityManagerFactory entityManagerFactory;

@Bean
public SessionFactory getSessionFactory() {
    if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
        throw new NullPointerException("Session factory is not available");
    }
    return entityManagerFactory.unwrap(SessionFactory.class);
}

}


Result:

When executing this project Run As -> Java Application

I am using Postman as a REST Client to hit the REST services.

1. http://localhost:8989/rest/allemps -> To get all the existing employees from DB. I have already inserted few records.




2. SAVE POST Request - http://localhost:8989/rest/save
JSON Data Format.{ "firstName": "gaurav", "lastName": "kumar", "email": "admin@gmail.com", "designation": "Lead Development"}


3. Employee By ID - http://localhost:8989/rest/emp/{ID}



No comments:

Post a Comment