是否可以使用Hibernate或JPA Annotations来限制@OneToMany集合的大小? [英] Is it possible to limit the size of a @OneToMany collection with Hibernate or JPA Annotations?
问题描述
如果我在使用JPA / Hibernate Annotations的POJO中拥有以下映射集合:
@OneToMany(mappedBy =columnName ,fetch = FetchType.LAZY)
@OrderBy(aField)
@MapKeyJoinColumn(name =id_fk)
@LazyCollection(value = LazyCollectionOption.EXTRA)
private设置< PojoClass> collection = new HashSet<>();
是否可以将加载的集合的大小限制为特定的数字n或设置页面大小延迟加载集合的前n个元素,而不加载该类的其他实例中的所有项目或任何其他项目(如@BatchSize)?
请注意,该问题显式引用了POJO映射,而不是额外的查询,使用Criteria或任何其他方式以编程方式限制显式查询中的大小。
我一直在寻找可能的解决方案在Hibernate中寻找SQL TOP语句的实现,希望作为一个注释或者创建一个自定义的CollectionPersister来修改生成的查询(尽管这需要在支持的方言中实现TOP语句)。
这是不可能的。 Hibernate有两种选择:
$ ul
没有中间立场。这是因为Hibernate需要管理整个集合实体状态转换。如果你能够加载子集,那么一个单向包没有什么意义。
虽然你可以使用 @Where
或 @Filter
,这些注释对于过滤集合的内容更有用,而不是限制其大小。
$ b $因此,您必须始终记住, Hibernate集合是一项功能,而非强制性要求。查询的方式更灵活,限制也更少。
所以,这次你必须使用查询:
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).
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
这篇关于是否可以使用Hibernate或JPA Annotations来限制@OneToMany集合的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!