Is it possible to limit the size of a @OneToMany collection with Hibernate or JPA Annotations?

That's not possible. Hibernate has two options for you:

  • you load the children collection upon fetching the parent entity
  • you load the children collection lazily on first access

There's no middle ground. That's because Hibernate needs to manage the whole collection entity state transitions. If you were able to load subsets then a unidirectional bag wouldn't make much sense.

While you can use @Where or @Filter, these annotations are more useful for filtering out the content of the collection, not to restrict its size.

So, you must always remember that [Hibernate collections are a feature, not a mandatory requirement. Queries are way more flexible and less limiting.

So, you have to use queries this time:

  • HQL/JPQL
  • Criteria
  • Native SQL

You could limit the amount of entries by using a "custom" join table name like so:

@JoinTable(name = "(select * from the_table order by some_column limit 10)")