[英]How to properly detach an Entity from Hibernate EntityManager
I wanted to test out JPA a little and so I created the following class User
: 我想测试一下JPA,所以我创建了以下类
User
:
@Entity
@Table(name="USER")
public class User {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="user")
private int user_id;
@Column(name="firstname")
private String firstname;
@Column(name="lastname")
private String lastname;
protected User() {
}
public User(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
//getters and setters
}
Now I got the following test-class: 现在,我获得了以下测试课程:
@RunWith(SpringRunner.class)
@DataJpaTest
public class AssignmentTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private UserRepository userRepository;
@Test
public void whenFindByName_thenReturnUser() {
//given
User user = new User("Firstname", "Lastname");
entityManager.persist(user);
entityManager.flush();
//when
User found = userRepository.findUsersByLastname(user.getLastname()).get(0);
entityManager.detach(user);
user.setLastname("Boohoo");
//then
assertThat(found.getLastname())
.isEqualTo("Lastname");
}
}
Now I'd like the entityManager to stop changing the value of my Entity. 现在,我希望entityManager停止更改我的实体的值。 I read a few posts that told to use
detach
, remove
or clear
- none of it worked out. 我读了几则文章,告诉他们使用
detach
, remove
或clear
,但都没有解决。 I still get (on test run): 我仍然得到(在测试运行中):
org.junit.ComparisonFailure: expected:<"[Lastname]"> but was:<"[Boohoo]">
I tried to see into the statements Hibernate is executing, but I cannot see that hibernate would execute an update
-statement. 我试图查看Hibernate正在执行的语句,但是我看不到hibernate将执行
update
-statement。
What did I do wrong on that? 我在这方面做错了什么?
In your example, user
and found
are pointing to the same object . 在您的示例中,
user
和found
指向同一对象 。
First, you call persist on user
, meaning that the object that user
references becomes a managed entity. 首先,您对
user
调用persist,这意味着user
引用的对象成为托管实体。 You then call: 然后,您致电:
User found = userRepository.findUsersByLastname(user.getLastname()).get(0);
and, since the User
that matches the query criteria is already present in the persistence context, a reference to that (previously persisted) object is returned. 并且,由于与查询条件匹配的
User
已经存在于持久性上下文中,因此将返回对该对象(以前是持久性的)的引用。
Calling entityManager.detach(user)
does detach the entity referenced by user
. 调用
entityManager.detach(user)
不会分离user
引用的实体。 It's just that found
references that very same object at this point. 只是
found
引用了相同的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.