java - hibernate 更新 : Why hibernate delete object before insert them after

标签 java hibernate

我使用 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/

相关文章:

java - 在 HIVE UDF 中返回 ArrayList<String>

java - Spring 框架项目未加载?

map 与列表中的 Java 缓存

java - 如何解决此 Log4J 导入错误(也与类路径有关)?

java - 将年份字段的日期转换为两位数时出错

Hibernate 自动将 1=2 附加到生成的查询

hibernate - 我应该在 MVC 架构中哪里使用 Hibernate Criteria?

java - 双向 OneToOne 被多次加载

Hibernate Criteria join 查询一对多

java - 将正则表达式添加到列表中以进行排序