使用额外的列休眠@ManyToMany



所以我一直在尝试用额外的列映射ManyToMany关系的解决方案,但它们都不适合我,我不知道我做错了什么。

多对多关系是患者和疾病之间的关系(一个患者可能患有多种疾病,一种疾病可能由许多患者患上(。时间属性表示"时间";疾病的类型";(急性、慢性…(

我的课程是:

@Entity
@Table(name="patient")
public class Patient{
@Id
@NotNull
@Column(name="nss")
private String NSS;

//Some attributes

@OneToMany(mappedBy = "patient")
private Set<PatientDisease> diseases = new HashSet<PatientDisease>();

//Empty constructor and constructor using fields omitted
//Getters and setters ommited
}

@Entity
@Table(name="disease")
public class Disease{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Integer id;

@OneToMany(mappedBy = "disease")
private Set<PatientDisease> patients = new HashSet<PatientDisease>();

//Constructors and getters and setters ommited for brevity
}

关联类

@Entity
@Table(name = "Patient_Disease")
@IdClass(PatientDiseaseID.class)
public class PatientDisease{
@Id 
@ManyToOne(fetch = FetchType.LAZY,
cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
@JoinColumn(name = "nssPatient", referencedColumnName = "id")
private Patient patient;

@Id
@ManyToOne(fetch = FetchType.LAZY,
cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
@JoinColumn(name = "diseaseID", referencedColumnName = "id")
private Disease disease;

@Column(name="time")
private String time;

//GETTERS AND SETTERS OMMITED FOR BREVETY. Constructor NOT Needed following the example
}

id类:

@Embeddable
public class PatientDiseaseId implements Serializable {
private static final long serialVersionUID = 1L;

@Column(name = "nssPatient")
private String patient;

@Column(name = "diseaseID")
private Integer disease;
//getters and setters
//hashCode and equals
}

我的主要应用程序:

...
List<Diseases> diseases = sesion.createQuery("from Disease").getResultList();
System.out.println("Diseases: ");
for(Disease d: diseases) {
System.out.println(d.getName());
for(PatientDisease pd: e.getPatientDisease()) {
System.out.println(pd.getPatient().toString());
}
}
...

当运行主应用程序时,我在第5行得到异常(第2行为循环(:线程中的异常";主";org.ibernate.PropertyAccessException:无法通过反射设置字段值[1]值:[class entitys.PatientDiseases.diseases]setter of entities。PatientDisease.diseases

我在Stack Overflow中尝试了一些解决方案,以及我在互联网上找到的其他解决方案,但我无法让它们发挥作用,我不知道为什么

因为您使用的是@IdClass,所以不需要用@Embedded@Column来注释PatientDiseaseId。你必须参考实体。

这就是它应该看起来的样子:

public class PatientDiseaseId implements Serializable {
private static final long serialVersionUID = 1L;

private Patient patient;

private Disease disease;
//getters and setters
//hashCode and equals
}