问题
I have two entity models, Customer and Order. Each customer could have thousands of orders. I have a OneToMany and ManyToOne relationship between these two entities.
How do I restrict this relationship's list to only top 10 orders?
Is it possible to apply 'WHERE' condition as an attribute on @OneToMany or not?
Like:
@OneToMany("Where Order.orderNo > 100")
My problem is when the object created by Entity Manager all Orders are created in memory. Lazy loading can not solve my consideration, because I need to get top 10 orders in default construction.
回答1:
I mean if it is possible to apply 'WHERE' condition as an attribute on @OneToMany or not?
Not with standard JPA. But some providers have extensions for this. For example, Hibernate does have a @Where
annotation:
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@Where(clause="1=1")
public Set<Ticket> getTickets() {
return tickets;
}
References
- Hibernate Annotations Reference Guide
- 2.4.6. Collection related annotations
回答2:
JPA does not support this. But in EclipseLink you can use an Expression to filter a relationship.
See, http://wiki.eclipse.org/EclipseLink/Examples/JPA/MappingSelectionCriteria
来源:https://stackoverflow.com/questions/3514672/how-to-apply-a-default-restriction-on-entity-bean-onetomany-relationships