我想在@ OneToMany中使用映射,但它会引发异常
org.hibernate.MappingException: Unable to read the mapped by attribute for moduleRoles in org.caau.entity.UserModuleRole!
这是我的实体mapping.UserModuleRole是复合类。如果使用注释代码,程序是正确的。有没有人帮我解决?
@Entity
@Table(name = "user")
public class User{
private long id;
private Set<UserModuleRole> moduleRoles;
@Id
@Column(name = "id", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
@OneToMany(fetch = FetchType.EAGER,mappedBy="user")
//if use under code,program is correct,but i want to use mappedBy!
//@OneToMany(fetch = FetchType.EAGER)
//@JoinColumn(name = "user_id")
public Set<UserModuleRole> getModuleRoles() {
return moduleRoles;
}
}
这里是UserModuleRole类
@Entity
@Table(name = "user_module_role")
@IdClass(UserModuleRolePK.class)
public class UserModuleRole{
private User user;
private ModuleRole moduleRole;
private long addUserId;
private Date addDate;
private long updateUserId;
private Date updateDate;
@Id
public User getUser() {
return user;
}
@Id
public ModuleRole getModuleRole() {
return moduleRole;
}
}
class UserModuleRolePK implements Serializable {
private static final long serialVersionUID = -9132981262254922539L;
private User user;
private ModuleRole moduleRole;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
public User getUser() {
return user;
}
@ManyToOne
@JoinColumns({ @JoinColumn(name = "module_id", nullable = false), @JoinColumn(name = "role_id", nullable = false) })
public ModuleRole getModuleRole() {
return moduleRole;
}
}
}
答案 0 :(得分:1)
首先,您获得的异常是由于user
类中没有任何名为UserModuleRole
的关系属性。
您要实现的目标是实体User
和ModuleRole
之间的多对多关系,不需要中间类UserModuleRole
在您的示例中,它所拥有的唯一字段/属性是对其他两个实体的外键引用。
除非您忘记在问题中添加更多信息,否则您应该使用的映射要简单得多,如下所示:
@Entity
public class ModuleRole {
private Long id;
private Set<User> users;
@Id
@Column(name = "id")
public Long getId() {
return id;
}
@ManyToMany
@JoinTable(name = "user_module_role",
joinColumns = @JoinColumn(name = "module_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "user_id"), referencedColumnName = "id")
public Set<Users> getUsers() {
return users;
}
}
@Entity
@Table(name = "user")
public class User{
private Long id;
private Set<ModuleRole> moduleRoles;
@Id
@Column(name = "id", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
@ManyToMany(mappedBy = "users")
public Set<ModuleRole> getModuleRoles() {
return moduleRoles;
}
}
Hibernate将自己处理中间表,除非你想在关系中添加其他字段,否则你不必担心它,在这种情况下this tutorial会有所帮助。