How to access entity manager with spring boot and

2019-02-03 10:01发布

How to get access to the entity manager in the repository when we use spring boot and spring data?

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

1条回答
beautiful°
2楼-- · 2019-02-03 10:31

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 CustomerRepositoryImpl implements CustomCustomerRepository {

    @PersistenceContext
    private EntityManager em;

    @Override
    public void customMethod() {

    }
}
查看更多
登录 后发表回答