[英]Hibernate. Generic Composite PK issue
我在Hibernate中使用復合主鍵時遇到問題。
例:
我有一個代表該類所有實例的基本主鍵的類。
public abstract class PrimaryKey implements Serializable { /* ... */ }
它除了實現java.io.Serializable接口外什么都沒有,並且可以在泛型或另一個類的方法中用作參數來縮小可接受的類。
另一個主鍵類應該繼承它,並將您的特定字段添加為鍵。 例如:
public class PassportPK extends PrimaryKey {
private String number;
private String series;
public PassportPK() {}
public PassportPK(String number, String series) {
this.number = number;
this.series = series;
}
// Getters/setters are below.
}
然后將其用於適當的實體中,如下所示:
@Entity
@Table(name = "T_PASSPORTS")
@IdClass(PassportPK.class)
public class Passport implements Serializable {
@Id
@Column(name = "F_NUMBER")
private String number;
@Id
@Column(name = "F_SERIES")
private String series;
public Passport() {}
// Getters/setters are below.
}
如果我與這樣的實體打交道,一切都會很好。
但是我項目中的某些實體具有簡單的主鍵,例如int,long,String等。
在這種情況下,我想擁有一個像這樣的通用主鍵:
public class SimplePK<T extends Serializable> extends PrimaryKey {
/**
* Represents a simple key field of entity (i.e. int, long, String, ...);
*/
private T id;
public SimplePK() {}
public SimplePK(T id) {
this.id = id;
}
public T getId() {
return this.id;
}
public void setId(T id) {
this.id = id;
}
}
問題:如何以注釋映射方式解決它?
ps當我嘗試像上一個示例中一樣解決它時(通過@IdClass(SimplePK.class)),我捕獲到"org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [application-context.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Property com.testprj.entity.SimplePK.id has an unbound type and no explicit target entity. Resolve this Generic usage issue or set an explicit target attribute (eg @OneToMany(target=) or use an explicit @Type"
異常。
pps我使用帶有Spring框架的Hibernate來連接組件。
我將不勝感激!
我認為您不能在id類中使用泛型類型。 使用@IdClass表示組合主鍵的類,如果只想使用一個屬性(如主鍵),則必須在聲明中使用@Id並刪除@IdClass。
例:
@Entity
@Table(name = "T_PASSPORTS")
public class Passport implements Serializable {
@Id
private String id; //Or int, long...
public Passport() {}
// Getters/setters are below.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.