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.

 

Let’s see some brief about EntityMnager 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 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.

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

 

Define the repository interface extending CrudRepository.

StudentRepository.java

Define service interface i.e StudentService.java

Define service implementation class.

StudentServiceImpl.java

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

Define the controller class or endpoint.

StudentController.java

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

Define the JpaConfig.java

Define the SpringMain.java

 

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

application.properties

 

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.

 

Top