0

I have class Template:

@Entity
@Table(name = "templates")
public class Template extends AbstractEntity {

    private List<AbstractField> fields;
}

It composes from fields, and I get any like quiz.

I have entities, whick inherits AbstractField:

@Setter
@MappedSuperclass
public abstract class AbstractField extends AbstractEntity {

    private FieldType fieldType;
    private String title;
    private Template template;
}

As we see, we have an abstract class of field (checkbox, radio button etc.), & all fields extends this abstract field, like below:

@Entity
@Table(name = "field_checkbox")
@Setter
@ToString
@EqualsAndHashCode(callSuper = true)
public class CheckBoxField extends AbstractField {

    private Boolean selection = false;
}

I need to link fields with one-to-many dependency. I did it with this way:

@Entity
@Table(name = "appeal_templates")
public class Template<F extends AbstractField> extends AbstractEntity {

    private List<F> fields;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "template")
    public List<F> getFields() {
        return fields;
    }
}

As we see, I decided to do it with generic. And I get exception:

Caused by: org.hibernate.AnnotationException: Property ru.model.representation.appeal.template.Template.fields has an unbound type and no explicit target entity. Resolve this Generic usage issue or set an explicit target attribute (eg @OneToMany(target=) or use an explicit @Type

As I understand, Hibernate not allow to map to generic. But I plan to store many types of fields, extended AbstractField. What to do?

1 Answers1

1

It's not possible to do with different tables for subclasses. Check this comment why

What you can do is to define single table inheritance type:

@Entity
@Table(name = "fields")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public abstract class AbstractField extends AbstractEntity {

    private FieldType fieldType;
    private String title;
    private Template template;
}

And then you can use List<AbstractField> fields in Template class.

DDovzhenko
  • 1,295
  • 1
  • 15
  • 34