在JPA中使用泛型映射抽象集合

时间:2017-07-29 15:35:32

标签: java generics jpa collections abstract

我有一个抽象的泛型类:

@MappedSuperclass
public abstract class Field<T> {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "field_id")
    private int id;

    @ManyToMany
    @JoinTable(name = "FIELD_SECTION")
    private List<Section> sections;
}

有几个类扩展它,例如:

@Entity
@Inheritance
public class StringField extends Field<String> {
}

@Entity
@Inheritance
public class DateField extends Field<Date> {
}

我还有一个Section类,它包含Field

的抽象集合
@Entity
public class Section {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "section_id")
    private int id;

    @ManyToMany(mappedBy = "sections")
    private List<Field<?>> fields;
}

但是,JPA无法正确映射List<Field<?>> fields集合,从而导致以下错误:

Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.model.Section.fields[com.model.field.Field]

基本上,它应该是可行的,因为FIELD_SECTION表将包含一对(section_id, field_id)。每种类型的字段都有一个单独的表,但所有field_id在所有字段表中都是唯一的,允许JPA确定每个字段的类型。

有没有办法实现上述目标?

0 个答案:

没有答案