2016-01-28 51 views
0

我在Hibernate中遇到了复合主键问题。休眠。通用复合PK问题

实施例:

我有代表的这样的所有实例基地主键的类。

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,串一个简单的主键,等

在这种情况下,我想有这样一个通用的主键:

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

问题:如何在注解映射中解决它?

p.s.当我试图解决它像前面的例子(通过@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的。

我会感谢任何帮助!

回答

0

我认为你不能在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. 

}

+1

我找到了解决方案:现在,我使用'@我的“通用” -primary键的表示Embeddable'类(继承主键基类) ,并在实体中指定其类型。将抽象的“PrimaryKey”类保存为所有主键实例的基础非常重要。 – Pasha190