Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access entity manager with spring boot and spring data

How can I get access to the Entity Manager in the repository when using Spring Boot and Spring Data?

Otherwise, I will need to put my big query in an annotation. I would prefer to have something more clear than a long text.

like image 832
robert trudel Avatar asked Jun 16 '15 17:06

robert trudel


People also ask

Why do we need EntityManager in Spring boot?

The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities. The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit.


Video Answer


1 Answers

You would define a CustomRepository to handle such scenarios. Consider you have CustomerRepository which extends the default spring data JPA interface JPARepository<Customer,Long>

Create a new interface CustomCustomerRepository with a custom method signature.

public interface CustomCustomerRepository {     public void customMethod(); } 

Extend CustomerRepository interface using CustomCustomerRepository

public interface CustomerRepository extends JpaRepository<Customer, Long>, CustomCustomerRepository{  } 

Create an implementation class named CustomerRepositoryImpl which implements CustomerRepository. Here you can inject the EntityManager using the @PersistentContext. Naming conventions matter here.

public class CustomCustomerRepositoryImpl implements CustomCustomerRepository {      @PersistenceContext     private EntityManager em;      @Override     public void customMethod() {          } } 
like image 111
Nitin Arora Avatar answered Oct 21 '22 02:10

Nitin Arora