One To Many
Unlike JPA, Jimmer does not support unidirectional one-to-many associations. One-to-many associations can only exist as mirrors of many-to-one associations. That is, one-to-many associations necessarily imply bidirectional associations.
In the following code:
-
Left:
Book.store
discussed in Many To One -
Right:
BookStore.books
to be discussed in this article, which is the mirror ofBook.store
- Java
- Kotlin
@Entity
public interface Book {
@ManyToOne
@JoinColumn(name = "STORE_ID")
BookStore store();
...Omit other code...
}
@Entity
interface Book {
@ManyToOne
@JoinColumn(name = "STORE_ID")
val store: BookStore
...Omit other code...
}
- Java
- Kotlin
@Entity
public interface BookStore {
// `mappedBy` indicates `BookStore.books`
// is the mirror of `Book.store`
@OneToMany(mappedBy = "store")
@Nullable
List<Book> books();
...Omit other code...
}
@Entity
interface BookStore {
// `mappedBy` indicates `BookStore.books`
// is the mirror of `Book.store`
@OneToMany(mappedBy = "store")
val books: List<Book>?
...Omit other code...
}
-
@OneToMany
associations are merely mirrors of@ManyToOne
associations.@JoinColumn
and@JoinTable
must not be used. -
The
@OneToMany
association property must be non-null. If the parent object is queried and its one-to-many association property needs to be fetched, then for the parent object that has no corresponding child objects, the value of this property is a collection of length 0 rather than null.