robert trudel
robert trudel

Reputation: 5779

How to access entity manager with spring boot and spring data

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.

Upvotes: 42

Views: 66763

Answers (2)

Sergey Ushakov
Sergey Ushakov

Reputation: 2483

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...

Upvotes: 3

Nitin Arora
Nitin Arora

Reputation: 2668

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

Upvotes: 40

Related Questions