【问题标题】:Hibernate Update : Why hibernate delete object before insert them after休眠更新:为什么在插入对象之前休眠删除对象
【发布时间】:2014-04-03 18:15:46
【问题描述】:

我使用 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: 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 (?, ?)

【问题讨论】:

  • 您似乎没有正确合并。您从子集合中有任何删除吗?另外,我建议您使用正确的hashCode()equals(),如果可能,请尝试使用Set 而不是List
  • 是的,这可能是您的合并问题。在更新前和更新后检查 users_project 表,检查它们的组合值是否改变。此外,序列化所有实体。

标签: java hibernate


【解决方案1】:

只是一个假设:

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

【讨论】:

    猜你喜欢
    • 2013-05-25
    • 2011-04-12
    • 2014-10-17
    • 2021-07-28
    • 2014-09-20
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    相关资源
    最近更新 更多