gpt4 book ai didi

java - 如何使用继承处理 JPA CollectionTable?

转载 作者:搜寻专家 更新时间:2023-11-01 00:54:56 24 4
gpt4 key购买 nike

我必须创建类的层次结构,其中父类(super class)具有表示 map 的 @CollectionTable。我试图实现它,但它只适用于一个子类。

我想做以下事情。我在左边有当前结构,在右边有所需的结构。 UML diagram of the structure

稳定(工作)代码如下所示:

@MappedSuperclass
public class Animal {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
}

@Entity(name = "cats")
@Audited
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.CHAR)
@DiscriminatorValue(value = Cat.PET_TYPE)
public abstract class Cat extends Animal {
public static final String PET_TYPE = "C";

@ElementCollection(fetch = FetchType.EAGER)
@MapKeyColumn(name = "name")
@Column(name = "value")
@CollectionTable(name = "cat_properties", joinColumns = @JoinColumn(name = "cat_id"))
private Map<String, String> properties = new HashMap<>();
}

@Audited
@Entity(name = "persiancats")
@DiscriminatorValue(value = PersianCat.PERSIAN_CAT_TYPE)
public class PersianCat extends Cat {
public static final String PERSIAN_CAT_TYPE = "P";
}

这就是我尝试实现修改的方式:

@MappedSuperclass
public class Animal {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
}

@MappedSuperclass
public abstract class Pet extends Animal {
@ElementCollection(fetch = FetchType.EAGER)
@MapKeyColumn(name = "name")
@Column(name = "value")
@CollectionTable(name = "pet_properties", joinColumns = @JoinColumn(name = "pet_id"))
private Map<String, String> properties = new HashMap<>();
}

@Entity(name = "cats")
@Audited
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.CHAR)
@DiscriminatorValue(value = Cat.PET_TYPE)
public class Cat extends Pet {
public static final String PET_TYPE = "C";
}

@Entity(name = "dogs")
@Audited
public class Dog extends Pet {
}

@Audited
@Entity(name = "persiancats")
@DiscriminatorValue(value = PersianCat.PERSIAN_CAT_TYPE)
public class PersianCat extends Pet {
public static final String PERSIAN_CAT_TYPE = "P";
}

Hibernate 创建了 pet_properties 表,但它只引用了 dogscats。我的意图是为狗和猫(以及波斯猫)属性创建一个通用表

我错过了什么或做错了什么?

最佳答案

我想您要实现的目标在逻辑上是不可能的,这就是原因(我偶然发现了同样的问题,尽管是在另一个领域)。要从您的 pet_properties 表中引用一个表,Hibernate 创建一个从 pet_properties 到目标表(在您的例子中是狗或猫)的外键。外键本质上意味着这个表中的每个条目都应该对应另一个表中的一个条目,而另一个表只是一个表。因此,如果您说您的 pet_properties 条目引用了 dogscats 表,那么它会立即破坏外键属性,因为如果它引用狗,则它不引用猫,反之亦然。

因此,Hibernate 为您提供的自动生成选项(单独的表 dogs_propertiescats_properties)似乎是正确的方法。

关于java - 如何使用继承处理 JPA CollectionTable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40020132/

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