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

Leave a Comment