@Entity
@Table(name="FOO")
public class Foo {
private UUID fooId;
@OneToMany
@JoinTable(name="FOO_BAR",
joinColumns = @JoinColumn(name="fooId"),
inverseJoinColumns = @JoinColumn(name="barId", unique=true))
private List<Bar> bars;
}
@Entity
@Table(name="BAR")
public class Bar {
private UUID barId;
//No Mapping specified here.
}
@Entity
@Table(name="FOO_BAR")
public class FooBar {
private UUID fooBarId;
@ManyToOne
@JoinColumn(name = "fooId")
private Foo foo;
@ManyToOne
@JoinColumn(name = "barId", unique = true)
private Bar bar;
//You can store other objects/fields on this table here.
}
Specifies a one-way relationship between one Foo
object to many Bar
objects using an intermediate join table that the user manages.
This is similar to a ManyToMany
relationship, but if you add a unique
constraint to the target foreign key you can enforce that it is OneToMany
.
The Foo
objects are stored as rows in a table called FOO
. The Bar
objects are stored as rows in a table called BAR
. The relationships between Foo
and Bar
objects are stored in a table called FOO_BAR
. There is a FooBar
object as part of the application.
Notice that there is no mapping of Bar
objects back to Foo
objects. Bar
objects can be manipulated freely without affecting Foo
objects.
Very commonly used with Spring Security when setting up a User
object who has a list of Role
's that they can perform. You can add and remove roles to a user without having to worry about cascades deleting Role
's.