Skip to main content

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 of Book.store

Book.java
@Entity
public interface Book {

@ManyToOne
@JoinColumn(name = "STORE_ID")
BookStore store();

...Omit other code...
}

mirror

BookStore.java
@Entity
public interface BookStore {

// `mappedBy` indicates `BookStore.books`
// is the mirror of `Book.store`
@OneToMany(mappedBy = "store")
@Nullable
List<Book> books();

...Omit other code...
}
caution
  • @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.