我使用 Hibernate 作为我项目的 orm 解决方案,但我不明白发生了什么。 我有一个实体用户:
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
...
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "users_projects", joinColumns = {
@JoinColumn(name = "userid")
},
inverseJoinColumns = {
@JoinColumn(name = "projectid")
})
private List<Project> projects;
... +getters and setters
}
我有项目实体。我对发生的事情感到惊讶: 如果用户有一些项目并且他想使用用户界面添加另一个项目。 Hibernate 首先删除当前用户数据库中的所有项目。然后将所有项目插入数据库。 为什么 hibernate 删除所有项目并在之后插入它们而不是只添加新项目。这是 Hibernate 日志:
Hibernate: select this_.code as code1_1_0_, this_.name as name2_1_0_ from country this_
Hibernate: insert into projects (besoins, countryCode, description, title) values (?, ?, ?, ?)
Hibernate: select last_insert_id()
Hibernate: update users set activated=?, email=?, lastError=?, password=?, profil_id =?, role=? where id=?
Hibernate: update profil set countryCode=?, countryName=?, description=?, firstname=?, lastName=?, phone=?, title=? where id=?
Hibernate: update projects set besoins=?, countryCode=?, description=?, title=? where id=?
Hibernate: update projects set besoins=?, countryCode=?, description=?, title=? where id=?
Hibernate: update projects set besoins=?, countryCode=?, description=?, title=? where id=?
Hibernate: update projects set besoins=?, countryCode=?, description=?, title=? where id=?
Hibernate: delete from users_projects where userid=?
Hibernate: insert into users_projects (userid, projectid) values (?, ?)
Hibernate: insert into users_projects (userid, projectid) values (?, ?)
Hibernate: insert into users_projects (userid, projectid) values (?, ?)
Hibernate: insert into users_projects (userid, projectid) values (?, ?)
Hibernate: insert into users_projects (userid, projectid) values (?, ?)
最佳答案
只是一个假设:
您的实体在更新前被检索和合并后已分离。实际上 hibernate 并没有跟踪集合上的变化,而是将其作为一个包进行管理
关于java - hibernate 更新 : Why hibernate delete object before insert them after,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22077020/