@ManyToMany
associationsMost often, you will need to use @JoinTable
annotation to specify the mapping of a many-to-many table relationship:
So, assuming you have the following database tables:
In the Post
entity, you would map this relationship, like this:
@ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(
name = "post_tag",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id")
)
private List<Tag> tags = new ArrayList<>();
The @JoinTable
annotation is used to specify the table name via the name
attribute, as well as the Foreign Key column that references the post
table (e.g., joinColumns
) and the Foreign Key column in the post_tag
link table that references the Tag
entity via the inverseJoinColumns
attribute.
Notice that the cascade attribute of the
@ManyToMany
annotation is set toPERSIST
andMERGE
only because cascadingREMOVE
is a bad idea since we the DELETE statement will be issued for the other parent record,tag
in our case, not to thepost_tag
record.
@OneToMany
associationsThe unidirectional @OneToMany
associations, that lack a @JoinColumn
mapping, behave like many-to-many table relationships, rather than one-to-many.
So, assuming you have the following entity mappings:
@Entity(name = "Post")
@Table(name = "post")
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
@OneToMany(
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();
//Constructors, getters and setters removed for brevity
}
@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {
@Id
@GeneratedValue
private Long id;
private String review;
//Constructors, getters and setters removed for brevity
}
Hibernate will assume the following database schema for the above entity mapping:
As already explained, the unidirectional @OneToMany
JPA mapping behaves like a many-to-many association.
To customize the link table, you can also use the @JoinTable
annotation:
@OneToMany(
cascade = CascadeType.ALL,
orphanRemoval = true
)
@JoinTable(
name = "post_comment_ref",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "post_comment_id")
)
private List<PostComment> comments = new ArrayList<>();
And now, the link table is going to be called post_comment_ref
and the Foreign Key columns will be post_id
, for the post
table, and post_comment_id
, for the post_comment
table.
Unidirectional
@OneToMany
associations are not efficient, so you are better off using bidirectional@OneToMany
associations or just the@ManyToOne
side.