如何使用继承处理JPA CollectionTable?

Csu*_*uki 5 java hibernate jpa

我必须创建一个类的层次结构,其中超类具有@CollectionTable表示地图的类.我试图实现它,但它只适用于一个子类.

我想做以下事情.我左边是当前结构,右边是所需结构. UML结构图

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

@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";
}
Run Code Online (Sandbox Code Playgroud)

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

@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";
}
Run Code Online (Sandbox Code Playgroud)

Hibernate创建pet_properties表但它只引用dogscats.我的目的是为狗和猫(和persiancat)属性创建一个公共表.

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

Csu*_*uki 0

删除这一@CollectionTable(name = "cat_properties", joinColumns = @JoinColumn(name = "cat_id"))行后,Hibernate 创建了两个表,一个名为 cats_properties(用于 cats 和 persiancats),另一个名为 dogs_properties。这并不完全是我想要的,这是两个实体的通用表,但它是可以接受的。