gpt4 book ai didi

java - Hibernate JPA 联合继承

转载 作者:行者123 更新时间:2023-11-30 08:01:50 25 4
gpt4 key购买 nike

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

enter image description here

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

基本项目:

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

物理元素:

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

一些硬件:

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

一些其他硬件:

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

这是我的问题:

我的其他表之一引用了 base_item 类,如果该类基于该 base_item_id 加载“some_hardware”或“some_other_hardware”,它会让我的生活变得更轻松。因此,我在该特定类上创建了这样的导航属性:

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

正如您可能已经猜到的,上面的方法不起作用。如果我尝试访问具有附加到实体的相关“SomeHardwarePojo”的“SomeNavigationClassPojo”,则会收到以下错误:

java.lang.IllegalArgumentException: Can not set SomeOtherHardwarePojo field SomeNavigationClass.someOtherHardware to SomeHardwarePojo.

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

最佳答案

您可以将属性添加为简单的 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' 的操作是不可能的。

关于java - Hibernate JPA 联合继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31808778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com