今天同事問了一個(gè)問題,關(guān)于annotation配置多對多關(guān)聯(lián)映射以后,創(chuàng)建新的對象時(shí)候,為什么多對多的關(guān)系沒有保存到關(guān)系表中。具體問題如下:
當(dāng)前有一個(gè)User和一個(gè)Role,它們是多對多關(guān)系,中間表為user_role存放user和role的id。部分User代碼如下:
@ManyToMany(cascade = { CascadeType.PERSIST }, fetch = FetchType.LAZY)
@JoinTable(name = "user_role",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public void addRole(Role role) {
if (!this.roles.contains(role)) {
this.roles.add(role);
}
}
public void removeRole(Role role) {
this.roles.remove(role);
}
Role中的部分代碼如下:
@ManyToMany(
cascade = {CascadeType.PERSIST, CascadeType.MERGE},
mappedBy = "roles",
targetEntity = User.class
)
public Set<User> getUsers() {
return users;
}
而測試代碼繼承了AbstractTransactionalJUnit4SpringContextTests,代碼如下:
@Test
public void testManyToMany() {
Role oneRole = new Role();
oneRole.setDescription("manager");
oneRole.setEnabled(true);
oneRole.setRoleName("manger");
Role twoRole = new Role();
twoRole.setDescription("waitress");
twoRole.setEnabled(true);
twoRole.setRoleName("waitress");
User user = new User();
user.setEnabled(true);
user.setPassword("jianghaiying");
user.setUsername("Jiang HaiYing");
user.addRole(oneRole);
user.addRole(twoRole);
userDAO.persist(user);
try {
userDAO.getConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
這樣執(zhí)行以后,打印出的信息如下:
Hibernate: insert into user (enabled, password, username) values (?, ?, ?)
Hibernate: insert into role (description, enabled, name) values (?, ?, ?)
Hibernate: insert into role (description, enabled, name) values (?, ?, ?)
這時(shí)候問題出來了,為什么沒有往關(guān)系表中插入數(shù)據(jù)?
其實(shí)這并不是代碼或者配置寫錯(cuò)誤了,在正式運(yùn)行代碼一切正常,而是AbstractTransactionalJUnit4SpringContextTests出的鬼,事實(shí)上多對多關(guān)聯(lián)關(guān)系是由Hibernate去幫我們維護(hù)的,而AbstractTransactionalJUnit4SpringContextTests為了保持?jǐn)?shù)據(jù)的清潔又會(huì)自動(dòng)回滾。如何解決這個(gè)問題呢?
方法:
只需要在test方法上添加
@Rollback(false),不讓它回滾,一切正常了。這時(shí)候也可以去掉try語句了。
Hibernate: insert into user (enabled, password, username) values (?, ?, ?)
Hibernate: insert into role (description, enabled, name) values (?, ?, ?)
Hibernate: insert into role (description, enabled, name) values (?, ?, ?)
Hibernate: insert into user_role (user_id, role_id) values (?, ?)
Hibernate: insert into user_role (user_id, role_id) values (?, ?)
posted on 2009-11-04 20:58
周銳 閱讀(4606)
評論(1) 編輯 收藏 所屬分類:
Hibernate 、
Junit 、
Spring