JPA: Does EntityManager.find() always return the same object reference for the same key?

后端 未结 2 1866
甜味超标
甜味超标 2021-01-20 16:29

I\'ve got an integration test of a DAO in which I use a shared EntityManager (via Spring, using SharedEntityManagerCreator). The test class is marked as @Transactional, as

相关标签:
2条回答
  • 2021-01-20 17:01

    find() returns the same instance inside a scope of persistence context.

    In the case of shared EntityManager (container-managed transaction-scoped persistence context, in JPA Spec terms) lifecycle of persistence context is bound to the transaction, therefore find() returns the same instance when called from the same transaction. I guess in your case setup of your test doesn't happen in the same transaction as a test method, so find() produces different instances.

    0 讨论(0)
  • 2021-01-20 17:15

    No it does not. You should rely on object EQUALITY instead of IDENTITY anyway. Override the equals method.

    0 讨论(0)
提交回复
热议问题