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.
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() {
}
}