为什么我们使用Session session = entityManager.unwrap(Session.class)?

Why do we use Session session = entityManager.unwrap(Session.class)?

我正在编写一个 DAO 文件并看到它被使用了很多次,但不清楚我们为什么使用它以及它的目的是什么。

entityManager 环绕 Session(除其他外)。

来自 unwrap

的 EntityManager 文档

Return an object of the specified type to allow access to the provider-specific API. If the provider's EntityManager implementation does not support the specified class, the PersistenceException is thrown.

因此,在您的情况下,您 知道 entityManager 有一个 Session 并且想要使用它 - 您 "unwrap it" 进入那个 class。

这是必要的,因为 转换 将不起作用