Issue
I am trying to use element collection in hibernate as below:
@Entity
class A{
private int id;
//more fields
@ElementCollection(targetClass = MyEnum.class)
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinTable(
name = "A_B",
joinColumns = @JoinColumn(name = "B_id"),
inverseJoinColumns = @JoinColumn(name = "A_id"))
@MapKeyColumn(name = "B_id")
@MapKeyClass(B.class)
@Enumerated(EnumType.STRING)
private Map<B, MyEnum> value = new HashMap<>();
//getters and setters
}
where A and B are two entities in MySQL and MyEnum is an enum.
But I am getting the following exception - Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: A.values[MyEnum.class].
The above exception arises when we are trying to use a class mapping which has not been declared an entity using the @Entity annotation but if we are using an enum, we need to use the @ElementCollection annotation along with the @Enumerated enum. I have done the same but the error persists.
Can you help me and let me know if I am doing anything wrong here? Thank you.
Solution
Just remove the @OneToMany
annotation : @ElementCollection
is enough :
@ElementCollection(targetClass = MyEnum.class)
@Enumerated(EnumType.STRING)
private Map<B, MyEnum> value = new HashMap<>();
and if you want to specify the table name and column names of the table used to store the collection :
@ElementCollection(targetClass = MyEnum.class)
@MapKeyJoinColumn(name = "B_id")
@MapKeyClass(B.class)
@CollectionTable(
name = "A_B",
joinColumns = @JoinColumn(name = "A_id"))
@Enumerated(EnumType.STRING)
private Map<B, MyEnum> value = new HashMap<>();
Answered By - Pierre Demeestere
Answer Checked By - Gilberto Lyons (JavaFixing Admin)