How to access entity manager with spring boot and spring data
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() {
}
}
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...
NOTE Demo code was simplified upon the first silent downvote received. Further downvoters, if any, are still encouraged to spend a minute for dropping at least a line of comment, as is there any sense in silent downvoting? :)