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

最后修改: 2022年 1月 23日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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.

我们可以通过创建一个自定义的存储库来获得EntityManager,该存储库扩展了例如内置的JpaRepository

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

首先,让我们定义一个Entity例如,对于我们要存储在数据库中的用户:

@Entity
public class User {
    @Id
    @GeneratedValue
    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:

使用@PeristenceContext,我们可以在实现类中注入EntityManager

public class CustomUserRepositoryImpl implements CustomUserRepository {

    @PersistenceContext
    private EntityManager entityManager;

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

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

同样,我们可以使用@PersistenceUnit注解,在这种情况下,我们将访问EntityManagerFactory,并从中访问EntityManager

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

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

@Repository
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 {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void givenCustomRepository_whenInvokeCustomFindMethod_thenEntityIsFound() {
        User user = new User();
        user.setEmail("foo@gmail.com");
        user.setName("userName");

        User persistedUser = userRepository.save(user);

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

3. Conclusion

3.总结

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.

像往常一样,这些例子的代码可以在GitHub上找到over