3

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 is the DAO method under test.

In both the test class and the DAO I'm retreiving a User entity as follows:

User user = em.find(User.class, "test");

In the setup of my test I've modified the user object, but I wasn't seeing the modification in the DAO when the test came to run. It turned out that the two references did not refer to the same object; I proved this in my test class using:

System.out.println("User objects equal = " + (user == dao.getUser()));

This printed out false. I would expect that every call to an EntityManager using the same key would return the same object reference, and was surprised (and a bit alarmed!) to find out this was not the case. Can anyone shed any light on this? I've refactored my code so it's not actually an issue (the DAO shouldn't have had the User object in it anyway) but I'd still like to understand this better.

Thanks!

Java 1.6u22, Toplink Essentials 2.0.1, Spring 2.5.6

4

2 に答える 2

6

find()永続コンテキストのスコープ内で同じインスタンスを返します。

共有EntityManager(コンテナ管理のトランザクションスコープの永続コンテキスト、JPA仕様の用語)の場合、永続コンテキストのライフサイクルはトランザクションにバインドされるためfind()、同じトランザクションから呼び出されたときに同じインスタンスを返します。あなたの場合、テストのセットアップはテストメソッドと同じトランザクションでは行われないためfind()、異なるインスタンスが生成されると思います。

于 2010-11-19T16:17:38.930 に答える
0

いいえ、違います。とにかく、IDENTITYではなくオブジェクトEQUALITYに依存する必要があります。equalsメソッドをオーバーライドします。

于 2010-11-19T16:05:11.413 に答える