Reputation: 186
I am trying to use @ElementCollection
with a set of classes which are all inherited from a @MappedSuperclass
but when persisting to the database there is no column to identify which subclass was created and therefore will fail when trying to retrieve it from the database. If I change the class to make it an entity instead it will then work but I need it to be @Embeddable
to work with @ElementCollection
Below is the code:
@Entity
public class A {
private String attr1;
private String attr2;
....
@ElementCollection
private List<B> list;
....
}
Superclass:
@Embeddable
@MappedSuperclass
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class B {
private String attr3
private String attr4
....
}
Subclass1:
@Embeddable
@DiscriminatorValue("B1")
public class B1 extends B {
private String attr5
....
}
Subclass2:
@Embeddable
@DiscriminatorValue("B2")
public class B2 extends B {
private String attr6
....
}
Thanks in advance
Upvotes: 0
Views: 713
Reputation: 16462
@ElementCollection
is for basic or embeddable values which both have no concept of inheritance. If you want inheritance, you need to model the value as entity and then use @OneToMany
. From a relational mapping perspective, the two mappings are almost the same:
@Entity
public class A {
private String attr1;
private String attr2;
....
@OneToMany(mappedBy = "a")
private List<B> list;
....
}
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class B {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "a_id")
private A a;
private String attr3
private String attr4
....
}
Upvotes: 1