我尝试使用多个映射属性。但是当我尝试运行代码时,代码会生成异常,这个例子是基于Pro JPA 2,第10章的书。有以下代码:
DeptID.java
public class DeptId implements Serializable{
private static final long serialVersionUID = 5177373337405448966L;
private int number;
private String country;
.....................
ProjectId.java
public class ProjectId implements Serializable{
private static final long serialVersionUID = 4239980609226293562L;
private String name;
private DeptId deptId;
.....................
Department.java
@Entity
@IdClass(DeptId.class)
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private int number;
@Id
private String country;
private String name;
@OneToMany(mappedBy="deptId")
List<Project> projects;
......................
Project.java
@Entity
@IdClass(ProjectId.class)
public class Project implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private String name;
@Id
@ManyToOne
@JoinColumn(name="dept_id")
private Department deptId;
........................
此代码将生成以下异常
Caused by: org.hibernate.AnnotationException: Implicit column reference in the @MapsId mapping fails, try to use explicit referenceColumnNames: example.domain.Department
答案 0 :(得分:2)
DeptID有两个主键,因此您不能拥有@JoinColumn(name="dept_id")
之类的内容。相反,使用这个:
@JoinColumns({
@JoinColumn(name="dept_number", referencedColumnName="number"),
@JoinColumn(name="dept_country", referencedColumnName="country")
})
如果仍然不起作用:在主键类(DeptID&amp; ProjectId)中尝试切换到public或保护私有属性。还检查他们是否有一个没有参数的构造函数,并实现equals&amp;哈希码方法。