Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If I have the following mapped collection in a POJO using JPA/Hibernate Annotations:

@OneToMany(mappedBy = "columnName", fetch = FetchType.LAZY) @OrderBy("aField") @MapKeyJoinColumn(name = "id_fk") @LazyCollection(value = LazyCollectionOption.EXTRA) private Set<PojoClass> collection = new HashSet<>(); 

Is it possible to limit the size of the loaded collection to a specific number n or to set the page size to lazy load the first n elements of the collection without loading all the items or any other items from other instances of the class (like with @BatchSize)?

Notice that the question explicitly refers to POJO mappings, not making additional queries, using Criteria or any other way to programmatically limit the size in explicit queries.

Possible solutions I've been looking at are finding an implementation of the SQL TOP statement within Hibernate, hopefully as an annotation or create a custom CollectionPersister to modify the generated query (although this would require having the TOP statement implemented within the supported dialects).

like image 270
rodrigobartels Avatar asked Oct 12 '14 17:10

rodrigobartels


People also ask

What is @column in hibernate?

The @Column annotation is defined as a part of the Java Persistence API specification. It's used mainly in the DDL schema metadata generation. This means that if we let Hibernate generate the database schema automatically, it applies the not null constraint to the particular database column.

How you will create OneToMany relationship in hibernate?

The way we do it in code is with @OneToMany. Let's map the Cart class to the collection of Item objects in a way that reflects the relationship in the database: public class Cart { //... @OneToMany(mappedBy="cart") private Set<Item> items; //... }


1 Answers

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
like image 142
Vlad Mihalcea Avatar answered Sep 22 '22 01:09

Vlad Mihalcea