How to Access EntityManager with Spring Data – 如何用Spring Data访问EntityManager

最后修改: 2022年 1月 23日

1. Overview


We usually don’t need to access the EntityManager directly when working on a Spring Data application. However, sometimes we may want to access it, for example, to create custom queries or to detach entities.

我们通常不需要访问EntityManager在处理 Spring Data 应用程序时直接访问。然而,有时我们可能想要访问它,例如,创建自定义查询或分离实体。

In this short tutorial, we’ll see how to access the EntityManager by extending a Spring Data Repository.

在这个简短的教程中,我们将看到如何通过扩展Spring Data Repository来访问EntityManager

2. Access EntityManager with Spring Data

2.用Spring Data访问EntityManager

We can get the EntityManager by creating a custom repository that extends, for instance, a built-in JpaRepository.


Firstly, let’s define an Entity, for example, for the users we want to store in a database:


public class User {
    private Long id;
    private String name;
    private String email;
    // ...

We don’t have direct access to the EntityManager in a JpaRepository. Therefore, we need to create our own.

我们不能直接访问JpaRepository 中的 EntityManager因此,我们需要创建我们自己的。

Let’s create one with a custom find method:


public interface CustomUserRepository {
    User customFindMethod(Long id);

Using @PeristenceContext, we can inject the EntityManager in the implementation class:


public class CustomUserRepositoryImpl implements CustomUserRepository {

    private EntityManager entityManager;

    public User customFindMethod(Long id) {
        return (User) entityManager.createQuery("FROM User u WHERE = :id")
          .setParameter("id", id)

Likewise, we can use the @PersistenceUnit annotation, in which case we’ll access the EntityManagerFactory and, from it, the EntityManager.


Finally, let’s create a Repository that extends both the JpaRepository and CustomRepository:

最后,让我们创建一个Repository,它同时扩展了JpaRepository CustomRepository

public interface UserRepository extends JpaRepository<User, Long>, CustomUserRepository {

In addition, we can make a Spring Boot application and test to check everything is tied up and working as expected:

此外,我们可以制作一个Spring Boot应用程序,并进行测试,以检查一切都已绑好并按预期工作。

@SpringBootTest(classes = CustomRepositoryApplication.class)
class CustomRepositoryUnitTest {

    private UserRepository userRepository;

    public void givenCustomRepository_whenInvokeCustomFindMethod_thenEntityIsFound() {
        User user = new User();

        User persistedUser =;

        assertEquals(persistedUser, userRepository.customFindMethod(user.getId()));

3. Conclusion


In this article, we looked at a quick example of accessing the EntityManager in a Spring Data application.

在这篇文章中,我们看了一个在Spring Data应用程序中访问EntityManager的快速示例。

We can access the EntityManager in a custom repository and still use our Spring Data Repository by extending its functionality.

我们可以在自定义存储库中访问EntityManager,并通过扩展其功能仍然使用我们的Spring Data Repository。

As always,  the code for these examples is available over on GitHub.