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.
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.
On
In case you have many repositories to deal with, and your need in EntityManager is not specific for any particular repository, it is possible to implement various EntityManager functionality in a single helper class, maybe something like that:
@Service
public class RepositoryHelper {
@PersistenceContext
private EntityManager em;
@Transactional
public <E, R> R refreshAndUse(
E entity,
Function<E, R> usageFunction) {
em.refresh(entity);
return usageFunction.apply(entity);
}
}
The refreshAndUse method here is a sample method to consume a detached entity instance, perform a refresh for it and return a result of a custom function to be applied to the refreshed entity in a declarative transaction context. And you can add other methods too, including query ones...
You would define a
CustomRepositoryto handle such scenarios. Consider you haveCustomerRepositorywhich extends the default spring data JPA interfaceJPARepository<Customer,Long>Create a new interface
CustomCustomerRepositorywith a custom method signature.Extend
CustomerRepositoryinterface usingCustomCustomerRepositoryCreate an implementation class named
CustomerRepositoryImplwhich implementsCustomerRepository. Here you can inject theEntityManagerusing the@PersistentContext. Naming conventions matter here.