Monday 4 June 2018

Hibernate and JPA Integration with Spring Boot

Spring Boot With Hibernate & MYSQL


Open http://start.spring.io/ to create a Spring Boot Project.

Selected dependencies for this project are : Web, JPA, MySQL, DevTools


After Generating the above project, use import project into Eclipse option.
File -> Import -> Existing Maven Project.



pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>spring.boot.hibernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>spring.boot.hibernate</name>
<description>Demo project for Spring Boot With Hibernate And MySQL</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>


</project>



JPA Entity or Model Class

package com.gaurav.spring.boot.hibernate.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 = "Employee")
public class Employee {

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

private String name;

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

public Employee() {
super();
}

public Employee(Long id, String name, String designation) {
super();
this.id = id;
this.name = name;
this.designation = designation;
}

public Employee(String name, String designation) {
super();
this.name = name;
this.designation = designation;
}

public Long getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", designation=" + designation + "]";
}

/**
* @return the designation
*/
public String getDesignation() {
return designation;
}

/**
* @param designation the designation to set
*/
public void setDesignation(String designation) {
this.designation = designation;
}
}

Repository class to read Employee entity information by extending CrudRepository

package com.gaurav.spring.boot.hibernate.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.gaurav.spring.boot.hibernate.model.Employee;



@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long> {

Employee findById(long empId);
Iterable<Employee> findAll();
}

/src/main/resources/application.properties

server.port=9595

# MySQL settings
spring.datasource.url=jdbc:mysql://IP:3306/experiment
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver.class=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect =org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false

# logging
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
logging.level.org.hibernate.SQL=debug

employee.sql

/*
SQLyog Community v11.52 (32 bit)
MySQL - 5.6.23-log 
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;

create table `employee` (
`id` bigint (10),
`name` varchar (150),
`designation` varchar (150)
); 
insert into `employee` (`id`, `name`, `designation`) values('10001','Aaditya','Senior Developer');
insert into `employee` (`id`, `name`, `designation`) values('11002','Gaurav','Technical Lead');
insert into `employee` (`id`, `name`, `designation`) values('51345','Kumar','System Analyst');


Spring Boot Initializer Class :- Application.java

package com.gaurav.spring.boot.hibernate;

import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

import com.gaurav.spring.boot.hibernate.model.Employee;
import com.gaurav.spring.boot.hibernate.repository.EmployeeRepository;

@SpringBootApplication
@ComponentScan("com.gaurav.spring.boot.hibernate.*")
public class Application implements CommandLineRunner {

private Logger logger = LoggerFactory.getLogger(this.getClass());

@Autowired
EmployeeRepository repository;

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

public static final String NEW_EMPLOYEE_NAME = "Sunita";

Long empId;

@Override
public void run(String... arg0) throws Exception {

logger.info("Finding a record based on passed empId", repository.findById(11002));

logger.info("First call for finding all users -> {}", repository.findAll());

Employee employee = new Employee();
employee.setName(NEW_EMPLOYEE_NAME);
employee.setDesignation("Senior Manager");

// Inserting a record into the database
logger.info("Inserting new employee, where employee name is: " + employee.getName(), repository.save(employee));

logger.info("Record with the employee " + employee.getName() + " inserted Successfully");

Iterator<Employee> employeeIterator = repository.findAll().iterator();
while (employeeIterator.hasNext()) {
Employee emp = employeeIterator.next();
if (emp.getName().equals(NEW_EMPLOYEE_NAME)) {
empId = emp.getId();
}
}

logger.info("Second call after insert a new Employee record for finding all users -> {}", repository.findAll());

// Updating a record into the database

logger.info("Update the employee record", repository.save(new Employee(empId, "Krishna", "Senior Manager")));

logger.info("Third call after insert a new Employee record for finding all users -> {}", repository.findAll());

// Deleting a record from the database
logger.info("Deleting a employee record, where employee id is:" + empId);
repository.deleteById(empId);

logger.info("Fourth call for finding all users after deleting an employee record whose employee id is " + empId
+ " -> {}", repository.findAll());

}
}

OUTPUT

2018-06-04 15:50:19 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_0_, employee0_.designation as designat2_0_0_, employee0_.name as name3_0_0_ from employee employee0_ where employee0_.id=?

2018-06-04 15:50:19 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Finding a record based on passed empId
2018-06-04 15:50:19 INFO  o.h.h.i.QueryTranslatorFactoryInitiator - HHH000397: Using ASTQueryTranslatorFactory
2018-06-04 15:50:19 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_, employee0_.designation as designat2_0_, employee0_.name as name3_0_ from employee employee0_

2018-06-04 15:50:19 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - First call for finding all users -> [Employee [id=10001, name=Aaditya, designation=Senior Developer], Employee [id=11002, name=Gaurav, designation=Technical Lead], Employee [id=51345, name=Kumar, designation=System Analyst]]
2018-06-04 15:50:19 DEBUG org.hibernate.SQL - insert into employee (designation, name) values (?, ?)

2018-06-04 15:50:20 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Inserting new employee, where employee name is: Sunita
2018-06-04 15:50:20 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Record with the employee Sunita inserted Successfully
2018-06-04 15:50:20 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_, employee0_.designation as designat2_0_, employee0_.name as name3_0_ from employee employee0_
2018-06-04 15:50:20 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_, employee0_.designation as designat2_0_, employee0_.name as name3_0_ from employee employee0_

2018-06-04 15:50:20 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Second call after insert a new Employee record for finding all users -> [Employee [id=10001, name=Aaditya, designation=Senior Developer], Employee [id=11002, name=Gaurav, designation=Technical Lead], Employee [id=51345, name=Kumar, designation=System Analyst], Employee [id=51355, name=Sunita, designation=Senior Manager]]

2018-06-04 15:50:20 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_0_, employee0_.designation as designat2_0_0_, employee0_.name as name3_0_0_ from employee employee0_ where employee0_.id=?

2018-06-04 15:50:20 DEBUG org.hibernate.SQL - update employee set designation=?, name=? where id=?
2018-06-04 15:50:20 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Update the employee record
2018-06-04 15:50:20 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_, employee0_.designation as designat2_0_, employee0_.name as name3_0_ from employee employee0_

2018-06-04 15:50:20 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Third call after insert a new Employee record for finding all users -> [Employee [id=10001, name=Aaditya, designation=Senior Developer], Employee [id=11002, name=Gaurav, designation=Technical Lead], Employee [id=51345, name=Kumar, designation=System Analyst], Employee [id=51355, name=Krishna, designation=Senior Manager]]

2018-06-04 15:50:20 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Deleting a employee record, where employee id is:51355
2018-06-04 15:50:20 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_0_, employee0_.designation as designat2_0_0_, employee0_.name as name3_0_0_ from employee employee0_ where employee0_.id=?
2018-06-04 15:50:20 DEBUG org.hibernate.SQL - delete from employee where id=?

2018-06-04 15:50:20 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_, employee0_.designation as designat2_0_, employee0_.name as name3_0_ from employee employee0_

2018-06-04 15:50:20 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Fourth call for finding all users after deleting an employee record whose employee id is 51355 -> [Employee [id=10001, name=Aaditya, designation=Senior Developer], Employee [id=11002, name=Gaurav, designation=Technical Lead], Employee [id=51345, name=Kumar, designation=System Analyst]]


No comments:

Post a Comment