我有以下域映射:
@Entity
@Table(name = "terminal_admin_role")
public class AdminRole {
@Id
@Column(name = "role_id", nullable = false, unique = true)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id")
@SequenceGenerator(name = "user_id", sequenceName = "user_id")
private Long adminId;
@Column(name = "role")
private String role;
public AdminRole(String role) {
this.role = role;
}
public AdminRole() {
}
// get set
@Override
public String toString(){
return role;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AdminRole)) {
return false;
}
AdminRole adminRole = (AdminRole) o;
if (!role.equals(adminRole.role)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return role.hashCode();
}
}
和
@Entity
@Table(name = "terminal_admin")
public class TerminalAdmin {
@ManyToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
@JoinTable(name = "admin_role", joinColumns = {
@JoinColumn(name = "admin_id", nullable = false) },
inverseJoinColumns = { @JoinColumn(name = "role_id",
nullable = false) })
private Set<AdminRole> adminRoles;
//...
}
并执行以下代码:
控制器:
@RequestMapping(value = "/admin/addNewAdmin")
public String adminUsers(@ModelAttribute @Valid TerminalAdmin terminalAdmin,
BindingResult bindingResult, ModelMap model, Principal principal, HttpSession session) {
...
terminalAdmin.setCreateDate(Calendar.getInstance());
terminalAdminService.saveTerminalAdmin(terminalAdmin);
...
}
服务:
@Override
@Transactional
public void saveTerminalAdmin(TerminalAdmin newAdmin) {
String rawPassword = newAdmin.getPassword();
newAdmin.setPassword(passwordEncoder.encode(newAdmin.getPassword()));
terminalAdminDao.save(newAdmin);
emailService.sendAdminCreatedEmail(rawPassword, newAdmin.getEmail(), newAdmin.getAdminRoles());
emailService.sendAdminRegisteredForAdminEmail(newAdmin);
}
DAO:
@Override
@Transactional
public void save(TerminalAdmin terminalAdmin) {
sessionFactory.getCurrentSession().save(terminalAdmin);
}
之后,我看到管理员角色绑定到数据库中AdminRole表中的用户重复。
我错了什么?我写过equals方法。
在保存调试之前我看到以下值:
答案 0 :(得分:1)
因为在您的新TerminalAdmin
中,它引用的AdminRole
不包含ID。 ID是实体的标识。它不使用equals()
来标识身份。如果没有ID,Hibernate只会将其视为新的AdminRole
来保存到DB(因为您在TerminalAdmin
中设置了相应的级联选项)
您可以选择
AdminRole
的ID更改为role
字符串,或/和AdminRole
字符串查找正确的role
字符串,并将其设置在新的TerminalAdmin
实体中,或/和AdminRole
ID等...