我的 hibernate 项目具有以下设计:
@MappedSuperclass
public abstract class User {
private List<Profil> profile;
@ManyToMany (targetEntity=Profil.class)
public List<Profil> getProfile(){
return profile;
}
public void setProfile(List<Profil> profile) {
this.profile = profile;
}
}
@Entity
@Table(name="client")
public class Client extends User {
private Date birthdate;
@Column(name="birthdate")
@Temporal(TemporalType.TIMESTAMP)
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date birthdate) {
this.birthdate= birthdate;
}
}
@Entity
@Table(name="employee")
public class Employee extends User {
private Date startdate;
@Column(name="startdate")
@Temporal(TemporalType.TIMESTAMP)
public Date getStartdate() {
return startdate;
}
public void setStartdate(Date startdate) {
this.startdate= startdate;
}
}
如您所见,用户与个人资料之间存在ManyToMany关系。
@Entity
@Table(name="profil")
public class Profil extends GObject {
private List<User> user;
@ManyToMany(mappedBy = "profile", targetEntity = User.class )
public List<User> getUser(){
return user;
}
public void setUser(List<User> user){
this.user = user;
}
}
如果现在尝试创建员工,则会出现 hibernate 异常:
我如何使用ManyToMany-Relationship对父类(super class)
User
进行概要分析,因此它适用于Client
和Employee
? 最佳答案
问题在于对User的引用,它不是一个实体。外键只能引用一个表。使用@ManyToAny(可以处理多个表),或者使用@Inheritance(strategy = InheritanceType.SINGLE_TABLE),它将所有实体都放在一个表上。
这是 hibernate 中有关继承的文档:http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#d0e1168
关于java - @ManyToMany在抽象的MappedSuperclass中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4045511/