编程语言
首页 > 编程语言> > java-混合联接和单表继承并查询所有对象

java-混合联接和单表继承并查询所有对象

作者:互联网

我有一个使用以下配置的Webapp(我更改了实体名称):

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "animals")
public abstract class Animal { ...

@MappedSuperclass
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Mammal extends Animal { ...

@Entity
@Table(name = "mammals")
@PrimaryKeyJoinColumn(name = "mammal_id")
@DiscriminatorValue(value = "dog")
public class Dog extends Mammal { ...

@Entity
@Table(name = "mammals")
@PrimaryKeyJoinColumn(name = "mammal_id")
@DiscriminatorValue(value = "cat")
public class Cat extends Mammal { ...

所以我有2张桌子:动物和哺乳动物.
除非我不完全了解该配置,否则此配置有效.
在哺乳动物中,继承类型从JOINED更改为SINGLE_TABLE,因此猫和狗存储在“哺乳动物”表中,而“哺乳动物_id”列将它们与“动物”表结合在一起.

问题是不可能以多态方式检索哺乳动物(猫或狗):

Mammal mammal = (Mammal) hibernateTemplate.get(Mammal.class, id);

或带有单个Hibernate查询的哺乳动物(狗和猫)列表:

List<Mammal> list = (List<Mammal>) hibernateTemplate.find("from Mammal");

我得到:“未知实体:哺乳动物”,因为哺乳动物不是实体,所以它只是一个映射的超类.

我尝试了几种配置更改,例如下面的更改.这似乎很有意义,但是在那种情况下,我得到了“无法加载实体:哺乳动物”,因为它查找的是猫和狗(不存在)表.

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "animals")
public abstract class Animal { ...

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "mammals")
@PrimaryKeyJoinColumn(name = "mammal_id")
@DiscriminatorColumn(name = "type")
public abstract class Mammal extends Animal { ...

@Entity
@DiscriminatorValue(value = "dog")
public class Dog extends Mammal { ...

@Entity
@DiscriminatorValue(value = "cat")
public class Cat extends Mammal { ...

因此,总结一下:我想使webapp保持相同的工作方式(2个表:动物和哺乳动物),但同时又可以执行多态查询:使用一个查询来检索哺乳动物(猫和狗)的列表.

我希望我足够清楚,并在此先感谢您的帮助.

另一个尝试:

“涉及下表的外键圆度依赖性:”

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "animals")
public abstract class Animal { ...

@Entity
@Table(name = "mammals")
@PrimaryKeyJoinColumn(name = "mammal_id")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Mammal extends Animal { ...

@Entity
@Table(name = "mammals")
@DiscriminatorValue(value = "dog")
public class Dog extends Mammal { ...

@Entity
@Table(name = "mammals")
@DiscriminatorValue(value = "cat")
public class Cat extends Mammal { ...

解决方法:

您是否尝试过hibernateTemplate.find(“来自哺乳动物”)?

查找查询需要使用JPA实体而不是表名.

BTW表通常以单数命名-通常会使复杂的查询读起来更好-例如在哪里chicken.id = egg.id

标签:java,inheritance,jpa,hibernate,hibernate-mapping
来源: https://codeday.me/bug/20191009/1882432.html