Tuesday, 27 August 2019

Spring boot data: How to get EntityManager

Using @PersistenceContext annotation, you can inject EntityManager to your spring application.

Example
@Repository
public class EmployeeDaoImpl implements EmployeeDao {

 @PersistenceContext
 private EntityManager entityManager;

 .....
 .....
}

Find the below working application.

App.java    
package com.sample.app;

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 org.springframework.data.jpa.repository.config.EnableJpaAuditing;

import com.sample.app.dao.EmployeeDao;
import com.sample.app.model.Employee;

@SpringBootApplication
@EnableJpaAuditing
public class App {

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

 @Bean
 public CommandLineRunner demo() {
  return (args) -> {
  
   Employee emp1 = new Employee();
   emp1.setFirstName("Sandeep");
   emp1.setLastName("Maj");
   
   Employee emp2 = new Employee();
   emp2.setFirstName("Swaroop");
   emp2.setLastName("kdp");
   
   empDao.save(emp1);
   empDao.save(emp2);
   
   empDao.all().forEach(System.out::println);
   
  };
 }

}

EmployeeDao.java
package com.sample.app.dao;

import java.util.List;

import com.sample.app.model.Employee;

public interface EmployeeDao {

 public void save(Employee emp);
 
 public List<Employee> all();
}

EmployeeDaoImpl.java
package com.sample.app.dao.impl;

import java.util.List;

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

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

import com.sample.app.dao.EmployeeDao;
import com.sample.app.model.Employee;

@Repository
public class EmployeeDaoImpl implements EmployeeDao {
 @PersistenceContext
 private EntityManager entityManager;

 @Override
 @Transactional
 public void save(Employee emp) {
  entityManager.persist(emp);
 }

 @Override
 public List<Employee> all() {
  Query query = entityManager.createQuery("select e from Employee e", Employee.class);
  return query.getResultList();
 }

}

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

import javax.persistence.Column;
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;

 @Column(name = "first_name")
 private String firstName;

 @Column(name = "last_name")
 private String 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=").append(id).append(", firstName=").append(firstName).append(", lastName=")
    .append(lastName).append("]");
  return builder.toString();
 }

}

application.properties
logging.level.root=WARN
logging.level.org.hibernate=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

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true

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>springJPA</groupId>
 <artifactId>springJPA</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>

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


  <dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
  </dependency>

 </dependencies>

</project>

Total project structure looks like below.


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

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

Hibernate: 
    
    drop table employees if exists
Hibernate: 
    
    drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: 
    
    create table employees (
       id integer not null,
        first_name varchar(255),
        last_name varchar(255),
        primary key (id)
    )
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    insert 
    into
        employees
        (first_name, last_name, id) 
    values
        (?, ?, ?)
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    insert 
    into
        employees
        (first_name, last_name, id) 
    values
        (?, ?, ?)
Hibernate: 
    select
        employee0_.id as id1_0_,
        employee0_.first_name as first_na2_0_,
        employee0_.last_name as last_nam3_0_ 
    from
        employees employee0_
Employee [id=1, firstName=Sandeep, lastName=Maj]
Employee [id=2, firstName=Swaroop, lastName=kdp]

You can download the complete working application from this link.
    


Previous                                                    Next                                                    Home

No comments:

Post a Comment