Hibernate JPA加入了继承

时间:2015-08-04 11:59:51

标签: java hibernate jpa

我有一个项目,其中包含使用@Inheritance(strategy = InheritanceType.JOINED)创建的部分数据结构。数据结构的这一部分看起来像这样:

enter image description here

设计基于思想in this article. 我使用Hibernate和JPA2接口作为我的数据层。上面的结构导致了以下pojo / dao类(省略了getter和setter):

BaseItem:

@Entity
@Table( name = "base_item" )
@Inheritance(strategy = InheritanceType.JOINED)
public class BaseItemPojo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
}

PhysicalItem:

@Entity
@Table( name = "physical_item" )
public class PhysicalItemPojo extends BaseItemPojo{
}

SomeHardware:

@Entity
@Table( name = "some_hardware" )
public class SomeHardwarePojo extends PhysicalItemPojo{
}

SomeOtherHardware:

@Entity
@Table( name = "some_other_hardware" )
public class SomeOtherHardwarePojo extends PhysicalItemPojo{
}

这是我的问题:

我的其他一个表中有一个对base_item类的引用,如果该类加载了" some_hardware"它会使我的生活变得更容易。或者" some_other_hardware"基于那个base_item_id。因此,我在该特定类上创建了这样的导航属性:

@Entity
@Table( name = "some_navigation_class" )
public class SomeNavigationClassPojo{
    @ManyToOne(optional = false)
    @JoinColumn(name="base_item_id", insertable = false, updatable = false)
    private BaseItemPojo baseItem;

    @ManyToOne
    @JoinColumn(name="base_item_id", insertable = false, updatable = false)
    private PhysicalItemPojo physicalItem;

    @ManyToOne()
    @JoinColumn(name = "base_item_id", insertable = false, updatable = false)
    private SomeHardwarePojo someHardwarePojo;

    @ManyToOne()
    @JoinColumn(name = "base_item_id", insertable = false, updatable = false)
    private SomeOtherHardwarePojo someOtherHardwarePojo;
}

正如您可能已经猜到的,上述情况并没有奏效。如果我尝试访问" SomeNavigationClassPojo"有一个相关的" SomeHardwarePojo"附加到实体,我收到以下错误:

  

java.lang.IllegalArgumentException:无法将SomeOtherHardwarePojo字段SomeNavigationClass.someOtherHardware设置为SomeHardwarePojo。

作为参考,我的目标是,如果数据库中不存在someHardwarePojo或someOtherHardwarePojo,则应将它们设置为null,而不是尝试映射到PhysicalItemPojo的相应其他子项

1 个答案:

答案 0 :(得分:1)

您可以将属性添加为简单的getter:

public class SomeNavigationClassPojo {
    ...
    public SomeHardwarePojo getSomeHardwarePojo() { 
        return baseItem instanceof SomeHardwarePojo ? (SomeHardwarePojo) baseItem : null; 
    }
    ...
}

主要缺点:您无法在JPA查询中使用这些属性 - 例如像SELECT n FROM SomeNavigationClassPojo n JOIN n.somehardwarepojo s WHERE s.propertyOfHardwarePojo = 'x'这样的东西是不可能的。