Hello! Recently I was stuck with such problem, and I hope the solution I provide below will help some other JPA newbies like me. If there is better solution please post it here!
The problem is as follows:
I want to create OneToMany relationship from classes Book
and CD
to class Tag
.
In order to unify all the logic regarding class Tag
from Book
and CD
I create @MappedSuperclass class Item
, and make Book
and CD
descendants of class Item
. But when I try to map
List <Tag>
tags with @OneToMany” in that superclass I get nothing good..
My solution:
In order to do an ORM mapping one should understand first what he actually wants to see in the database. So when I realized that reasonable solution is to create several transition tables between descendants of Item
and Tag
, I understood, that this may be accomplished using @ManyToMany. And it works fine!
Listing below.
@MappedSuperclass
public class Item extends Model {
@Id
public Long id;
@ManyToMany(cascade = CascadeType.ALL)
public List<Tag> tags;
public String name;
<…> }
@Entity
public class Book extends Item {
public int pageNum;
<…> }
@Entity
public class CD extends Item{
public int size;
<…> }
@Entity
public class Tag extends Model{
@Id
public Long id;
public String text;
<…> }
PS I'd post also class and er diagrams, but currently I got no r8n to post images.