How to get JPA EntityManager in Spring Boot

Sometime you might want JPA EntityManager reference in your spring boot and Spring Data JPA application. Let’s see how to get JPA EntityManager in Spring Boot.

Get JPA EntityManager in Spring Boot using @PersistenceContext.

@PersistenceContext
private EntityManager entityManager;

Note – Make sure you have Spring Data JPA dependency in pom.xml to get entityManager using @PersistentContext.

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

Let’s see an example.

package com.netsurfingzone.impl;

@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {

	@PersistenceContext
	private EntityManager entityManager;

	@Transactional
	public Student saveStudent(Student student) {
		entityManager.persist(student);
		return student;
	}
	
}

Let’s see some brief about EntityManager and @PersistenceContext.

Basic points about EntityManager and @PersistenceContext.

EntityManager.

The JPA EntityManager is available in javax.persistence package used to interact with the persistence context. Let’s see some important methods of EntityManager.

contains(Object entity) – Used to check Check managed entity instance are there in the current persistence context or not.

find(Class entityClass, Object primaryKey) – Get an entity from database using the primary key.

remove(Object entity) – Used to delete an entity.


merge(T entity) – Used to merge the given entity into the current persistence context. See an example here.

persist(Object entity) – Used to persist entity into the database. See an example here.

getDelegate() – Return the underlying provider object for the EntityManager. For example, we can get a session object using entityManager .

getFlushMode() – Get the flush mode of objects in the persistence context.

clear() – Used to clear the persistence context.

close() – Used to close entity manager.

@PersistenceContext.

The PersistenceContext interface is available in javax.persistence package.

This annotation can be used with class, method and Field.

The persistence context contains entity instances and used to manage the entity instances life cycle.

Get JPA EnityManager From Hibernate Session.

Suppose you are using Hibernate Session in your application. Now you need JPA EntityManger. We can get EntityManger from Hibernate session using EntityManagerFactory. First, we will create EntityManagerFactory, the EntityManagerFactory has createEntityManager() method, using that we can get EntityManger.

public Student getStudent(Long id) {
	SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
	Session session = sessionFactory.openSession();
	EntityManager em = session.getEntityManagerFactory().createEntityManager();
	return em.find(Student.class, id);
}

Get JPA EntityManager in Spring Boot using Custom Configuration.

Let’s see how to configure EntityManager for Spring Data JPA.


Configure the Datasource.

@Bean
public DataSource dataSource() {

String username = env.getProperty("spring.datasource.username");
String password = env.getProperty("spring.datasource.password");
String driverClass = env.getProperty("spring.datasource.driver-class-name");
String url = env.getProperty("spring.datasource.url");

return DataSourceBuilder.create().username(username).password(password).url(url).driverClassName(driverClass)
.build();
}

Configure the JpaTransactionManager.

@Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}

Configure the EntityManagerFactory.

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);

return entityManagerFactoryBean;
}

The complete example of getting EntityManager using the custom configuration in Spring Boot.

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’click on next. Fill all details(GroupId – entitymanager, ArtifactId – entitymanager and name – entitymanager) and click on finish. Keep packaging as the jar.

Modify the pom.xml with the below code.

<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>entitymanager</groupId>
	<artifactId>entitymanager</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>entitymanager</name>
	
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
 
		</dependency>
 
		<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
 
		<dependency>
		<groupId>com.oracle</groupId>
		<artifactId>ojdbc6</artifactId>
		<version>11.2.0.3</version>
		</dependency>
 
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>
 
		<plugin>
		<artifactId>maven-compiler-plugin</artifactId>
		<version>3.1</version>
		<configuration>
		<fork>true</fork>
		<executable>C:\Program Files\Java\jdk1.8.0_131\bin\javac.exe</executable>
		</configuration>
		</plugin>
 
 
		</plugins>
	</build>
</project>

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

If you see any error for oracle dependency then follow these steps.

The directory structure of the application.

How to get JPA EntityManager in Spring Boot

Define entity class i.e Student.java.

Student.java

package com.netsurfingzone.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Student {

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

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

	@Column(name = "roll_number")
	private String rollNumber;

	@Column(name = "university")
	String university;

	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 getRollNumber() {
		return rollNumber;
	}

	public void setRollNumber(String rollNumber) {
		this.rollNumber = rollNumber;
	}

	public String getUniversity() {
		return university;
	}

	public void setUniversity(String university) {
		this.university = university;
	}

}

Define the repository interface extending CrudRepository.


StudentRepository.java

package com.netsurfingzone.repository;

import java.io.Serializable;

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

import com.netsurfingzone.entity.Student;

@Repository
public interface StudentRepository extends CrudRepository<Student, Serializable> {

}

Define service interface i.e StudentService.java

package com.netsurfingzone.service;

import org.springframework.stereotype.Component;

import com.netsurfingzone.entity.Student;

@Component
public interface StudentService {
	public Student saveStudent(Student student);

	public Student getStudent(int id);

}

Define service implementation class.

StudentServiceImpl.java

package com.netsurfingzone.impl;

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

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

import com.netsurfingzone.entity.Student;
import com.netsurfingzone.repository.StudentRepository;
import com.netsurfingzone.service.StudentService;

@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentRepository studentRepository;

	@PersistenceContext
	private EntityManager entityManager;

	@Transactional
	public Student saveStudent(Student student) {
		Student response = studentRepository.save(student);
		return response;
	}

	@Transactional(readOnly = true)
	public Student getStudent(int id) {
		// Optional<Student> studentResponse = studentRepository.findById(id);
		Student student = entityManager.find(Student.class, id);
		return student;
	}

}

Note – See here more about @Component, @Controller, @Service and @Repository annotations here.

Define the controller class or endpoint.

StudentController.java

package com.netsurfingzone.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.netsurfingzone.entity.Student;
import com.netsurfingzone.service.StudentService;

@RestController
@RequestMapping(value = "/student")
public class StudentController {

	@Autowired
	private StudentService studentService;

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Student save(@RequestBody Student student) {
		Student studentResponse = (Student) studentService.saveStudent(student);
		return studentResponse;
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Student getStudent(@PathVariable int id) {
		Student studentResponse = (Student) studentService.getStudent(id);
		return studentResponse;
	}

}

Note – See more details about @Controller and RestController here.

Define the JpaConfig.java

package com.netsurfingzone.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableJpaRepositories(basePackages = "com.netsurfingzone.repository", transactionManagerRef = "jpaTransactionManager")
@PropertySource(value = { "classpath:config.properties" })
@EnableTransactionManagement
public class JpaConfig {

	private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = { "com.netsurfingzone.entity" };

	@Autowired
	private Environment env;

	@Bean
	public DataSource dataSource() {

		String username = env.getProperty("spring.datasource.username");
		String password = env.getProperty("spring.datasource.password");
		String driverClass = env.getProperty("spring.datasource.driver-class-name");
		String url = env.getProperty("spring.datasource.url");

		return DataSourceBuilder.create().username(username).password(password).url(url).driverClassName(driverClass)
				.build();
	}

	@Bean
	public JpaTransactionManager jpaTransactionManager() {
		JpaTransactionManager transactionManager = new JpaTransactionManager();
		transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
		return transactionManager;
	}
	
    //adding for future use
	private HibernateJpaVendorAdapter vendorAdaptor() {
		HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
		return vendorAdapter;
	}

	@Bean
	public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

		LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
		entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
		entityManagerFactoryBean.setDataSource(dataSource());
		entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
		entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
		entityManagerFactoryBean.setJpaProperties(addProperties());

		return entityManagerFactoryBean;
	}

	private Properties addProperties() {
		Properties properties = new Properties();
		properties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
		properties.setProperty("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect"));
		properties.setProperty("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));
		properties.setProperty("hibernate.format_sql", env.getProperty("spring.jpa.properties.hibernate.format_sql"));
		// we can add 
		return properties;
	}

}

Define the SpringMain.java

package com.netsurfingzone.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = "com.*")
public class SpringMain {
	public static void main(String[] args) {

		SpringApplication.run(SpringMain.class, args);
	}

}

And finally, we have an application.properties file where we have database details.

application.properties

# Connection url for the database
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=SYSTEM
spring.datasource.password=oracle3
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
# Show or not log for each sql query
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.format_sql=true 
 
spring.jpa.hibernate.ddl-auto =create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
 
server.port = 9091
 
#show sql values
logging.level.org.hibernate.type.descriptor.sql=trace
 
#hibernate.show_sql = true
#spring.jpa.hibernate.logging.level.sql =FINE
#show sql statement
#logging.level.org.hibernate.SQL=debug

Let’s deploy the application running SpringMain class as a java application.

That’s all about How to get JPA EntityManager in Spring Boot.

You may like.

Hibernate/JPA association and inheritance mapping.

EntityManager docs.