复合键与hibernate中的子类

时间:2014-06-02 09:45:23

标签: java hibernate hibernate-mapping hibernate-annotations

我有一个班级系统

@Entity
abstract class System{
@Id
int systemId;
//setter and getters..
}

并且按类扩展

@Entity
class PhysicalSystem extends System
{
@Id
int place;
//setter and getters..
}

需要使用systemId和place来制作复合键 我怎么能这样做..如果我在这两个类中都有@Id它的抛出异常

Initial SessionFactory creation failed.java.lang.ClassCastException: org.hibernate.mapping.JoinedSubclass cannot be cast to org.hibernate.mapping.RootClass

我该如何解决这个问题?

表:

System{
systemid PK
systemName
}

PhysicalSystem
{
systemId PK
locationId PK
}

1 个答案:

答案 0 :(得分:0)

在您的情况下,最好的解决方案可能是OneToOne映射:

@Entity
public class PhysicalSystem implements Serializable {

    @EmbeddedId
    private PhysicalSystemKey key;  

    @JoinColumns({JoinColumn(name = "key.systemId", referencedColumnName = "ctvId"})
    @OneToOne(mappedBy = "physicalSystem")
    private System system;

    // ...
}

@Embeddable
public class PhysicalSystemKey {

    private Long systemId;

    private Long locationId;

    // ...
}

@Entity
public class System implements Serializable {

    @Id
    private Long systemId;

    @OneToOne(mappedBy = "system")
    private PhysicalSystem physicalSystem;
}