2
我使用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 (?, ?)
看來你沒有正確的合併。你有沒有從兒童收藏中刪除?另外,我建議你有適當的'hashCode()'和'equals()',如果可能的話嘗試使用'Set'而不是'List'。 –
是的,這可能是你的合併問題。更新前檢查users_project表,更新後檢查它們的組合值是否更改。另外,序列化所有的實體。 – Zeus
的可能的複製[爲什麼Hibernate的嘗試刪除時,我嘗試更新/插入?](http://stackoverflow.com/questions/179259/why-does-hibernate-try-to-delete-when-i-try -to-更新插入?RQ = 1) –