条件说明:在用户注册时候,选择role,然后再插入到数据库表中的user和user_role表中。
下面实体配置中的cascade=CascadeType.MERGE,当删除某个user的时候,它同样也会级联的删除与其相关联的表中的数据。而只需要在后台用User user = this.getJpaTemplate().find(User.class, id); this.getJpaTemplate().remove(user);这样就可以轻松的搞定级联删除了。
1.User实体
@Entity
@Table(name = "user")
public class User implements Serializable {
@ManyToMany(fetch=FetchType.LAZY,cascade=CascadeType.MERGE)
@JoinTable(name="user_role",
joinColumns=
@JoinColumn(name="user_id", referencedColumnName="ID"),
inverseJoinColumns=
@JoinColumn(name="role_id", referencedColumnName="ID")
)
private Set roleCollection = new HashSet();
}
2.Role实体
@Entity
@Table(name = "role")
public class Role implements Serializable {
@ManyToMany(mappedBy="roleCollection")
private Set userCollection;
}
这样设置好实体后,逻辑代码是:
public String signupSubmit(){
role = roleService.getRoleById(roleId);
user.getRoleCollection().add(role);
userService.insert(user);
return "signupSubmit".trim();
}
这样就可以插入到user和user_role表中了。注意这里不用设置中间表的实体了,不管它任何事情。
下面是错误的实体写法(它和中间表有关系了,最好不要这样写)
User实体(不支持的写法)
@Entity
@Table(name = "user")
public class User implements Serializable {
private Set userRoles = new HashSet(0);
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
public Set getUserRoles() {
return this.userRoles;
}
public void setUserRoles(Set userRoles) {
this.userRoles = userRoles;
}
}
Role实体:(不支持的写法)
@Entity
@Table(name = "role")
public class Role implements Serializable {
private Set userRoles = new HashSet(0);
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "role")
public Set getUserRoles() {
return this.userRoles;
}
public void setUserRoles(Set userRoles) {
this.userRoles = userRoles;
}
}
UserRole实体:
@Entity
@Table(name = "user_role")
public class UserRole implements java.io.Serializable {
private User user;
private Role role;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id")
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "role_id")
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
}
如果按照上面那种“不支持的写法”写了后,你不妨试下下面的代码或许能插入成功。
role = roleService.getRoleById(roleId);
UserRole userRole = new UserRole();
userRole.setRole(role);
userRole.setUser(user);
Set userRoles = new HashSet();
userRoles.add(userRole);
user.setUserRoles(userRoles);
userService.insert(user);
如果插入成功则证明这样也是可以的,因为我的总是插入不成功(但是我同事的好像这样就可以插入成功,我至今都不知道是什么原因),可以是实体或者数据库或者其他的原因。 我的总报告错误是:During synchronization a new object was found through a relationship that was not marked cascade PERSIST。望高手指点!