JPA Relations: Overview
Overview of the existing relation types in the Jakarta Persistence API.
With the Jakarta Persistence API (JPA), it is very easy to define relations between database entities. However, the number of possible combinations and customizations might lead to confusion from time to time. The following tables provide a brief overview of the basic use cases, and can serve as a starting point for domain-specific adaptations.
First, let’s begin with the most common use cases, where entities “A” and “B” share a bidirectional relation:
Entity "A" | Entity "B" |
---|---|
@OneToOne @JoinColumn(name="B_ID") B b; |
@OneToOne(mappedBy="b") A a; |
@ManyToOne @JoinColumn(name="B_ID") B b; |
@OneToMany(mappedBy="b") List<A> as; |
@ManyToMany @JoinTable( name="A2B", joinColumns=@JoinColumn(name="A_ID"), inverseJoinColumns=@JoinColumn(name="B_ID")) List<B> bs; |
@ManyToMany(mappedBy="bs") List<A> as; |
Note that in the previous table,
- the @JoinColumn refers to a database column of the current entity (not of the referenced entity)
- the mappings in entity “B” can be skipped if a unidirectional relation is sufficient
Next, we can also define a separate join table instead of a join column. This might be necessary when dealing with a legacy database. Otherwise, you are probably better off by using simple join columns where this is possible.
Entity "A" | Entity "B" |
---|---|
@OneToOne @JoinTable( name="A2B", joinColumns=@JoinColumn(name="A_ID"), inverseJoinColumns=@JoinColumn(name="B_ID")) B b; |
@OneToOne(mappedBy="b") A a; |
@ManyToOne @JoinTable( name="A2B", joinColumns=@JoinColumn(name="A_ID"), inverseJoinColumns=@JoinColumn(name="B_ID")) B b; |
@OneToMany(mappedBy="b") List<A> as; |
And finally, it is also possible to model a unidirectional @OneToMany relation (though probably not the best way of doing things, as described in an article by Vlad Mihalcea). Note that in this case, the @JoinColumn refers to a column in the other database table:
Entity "A" | Entity "B" |
---|---|
@OneToMany @JoinColumn(name="A_ID") List<B> bs; |
- |
The full source code can be found on GitHub.