Hibernate Update:为什么在插入之前将hibernate删除对象

时间:2014-02-27 18:19:32

标签: 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 (?, ?)

1 个答案:

答案 0 :(得分:0)

只是一个假设:

您的实体在更新之前被检索并合并后已分离。实际上,hibernate没有跟踪集合的变化,因此将其作为一个包来管理