2013-02-01 85 views
2

我嘗試使用多個映射的屬性。但是當我嘗試運行代碼時,代碼將生成異常,此示例基於Pro JPA 2第10章的書。有以下代碼:JPA 2:@MapsId映射中的隱式列引用失敗

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; 
    ........................ 

這個代碼將產生follwoing例外

Caused by: org.hibernate.AnnotationException: Implicit column reference in the @MapsId mapping fails, try to use explicit referenceColumnNames: example.domain.Department 

回答

2

DEPTID有兩個主鍵,這樣你就可以不必像@JoinColumn(name="dept_id")。相反,使用這樣的:

@JoinColumns({ 
    @JoinColumn(name="dept_number", referencedColumnName="number"), 
    @JoinColumn(name="dept_country", referencedColumnName="country") 
}) 

如果這仍然不起作用:在主鍵類(DEPTID &專案編號)嘗試切換到公共或保護的私有屬性。還要檢查它們是否有一個沒有參數的構造函數,並實現等於&散列碼方法。