Sunday 15 March 2020

Spring jpa: Get Hibernate session object from EntityManager

‘entityManager.unwrap’ method is used to get hibernate session object.

Example
Session session = entityManager.unwrap(Session.class);

Find the below working application.

Employee.java
package com.sample.app.entity;

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

@Entity
@Table(name = "employees")
public class Employee {

  @Id
  @GeneratedValue
  private int id;

  private String firstName;;

  private String lastName;

  public Employee() {
  }

  public Employee(String firstName, String lastName) {
    super();
    this.firstName = firstName;
    this.lastName = lastName;
  }

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

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("Employee [id=");
    builder.append(id);
    builder.append(", firstName=");
    builder.append(firstName);
    builder.append(", lastName=");
    builder.append(lastName);
    builder.append("]");
    return builder.toString();
  }

}

EmployeeRepository.java
package com.sample.app.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sample.app.entity.Employee;

@Repository
@Transactional
public class EmployeeRepository {

  @PersistenceContext
  private EntityManager entityManager;

  public Session getSession() {
    Session session = entityManager.unwrap(Session.class);
    return session;
  }

  public List<Employee> all() {
    Session session = getSession();
    Query query = session.createQuery("FROM Employee");
    return query.getResultList();
  }

  public void save(Employee emp) {

    getSession().save(emp);

  }

}

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.sample.app</groupId>
  <artifactId>springJPASession</artifactId>
  <version>1</version>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>


  </dependencies>
</project>

Create application.properties file under src/main/resources folder.

application.properties
# Setting log level to DEBUG
logging.level.org.springframework.web=ERROR

## H2 specific properties
spring.h2.console.enabled=true
spring.h2.console.path=/h2

spring.datasource.url=jdbc:h2:file:~/db/myOrg.db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1;

spring.datasource.username=krishna
spring.datasource.password=password123

spring.datasource.driverClassName=org.h2.Driver

## JPA specific properties
# Creates the schema, destroying previous data.
spring.jpa.hibernate.ddl-auto=create

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

## Database connection pooling properties
# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.max-wait=10000

# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=10
spring.datasource.tomcat.max-idle=5
spring.datasource.tomcat.min-idle=3

App.java
package com.sample.app;

import java.util.List;

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.Bean;

import com.sample.app.entity.Employee;
import com.sample.app.repository.EmployeeRepository;

@SpringBootApplication
public class App {
  
  @Autowired
  private EmployeeRepository employeeRepo;
  
  public static void main(String args[]) {
    SpringApplication.run(App.class, args);
  }

  @Bean
  public CommandLineRunner demo() {
    return (args) -> {

      Employee emp1 = new Employee("Ram", "Gurram");
      Employee emp2 = new Employee("Sai", "Nidamanuri");
      Employee emp3 = new Employee("Siva", "Ponnam");
      Employee emp4 = new Employee("Lahari", "Gurram");

      employeeRepo.save(emp1);
      employeeRepo.save(emp2);
      employeeRepo.save(emp3);
      employeeRepo.save(emp4);

      List<Employee> emps = employeeRepo.all();

      System.out.println("-------------------------");
      System.out.println("Printing Employees");
      System.out.println("-------------------------");
      for (Employee emp : emps) {
        System.out.println(emp);
      }

    };
  }

}

Total project structure looks like below.



Run App.java, you will see below messages in console.

-------------------------
Printing Employees
-------------------------
Employee [id=1, firstName=Ram, lastName=Gurram]
Employee [id=2, firstName=Sai, lastName=Nidamanuri]
Employee [id=3, firstName=Siva, lastName=Ponnam]
Employee [id=4, firstName=Lahari, lastName=Gurram]

You can download complete working application from this link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment