Reputation: 11267
With JPA, can I run a query after an object is loaded from the database?
For example, I have an entity that has this field:
@OneToMany(mappedBy = "widget", fetch = FetchType.EAGER, cascade = {})
@OrderBy("happenedDate DESC")
public List<Widget> getWidgets() {
return widgets;
}
This will only load all of the associated widgets. What I really want are the first 20 in the result set with the order by the happenedDate
. Is there an annotation that can specify a method to run after my object is loaded from the DB so I can run a query and get limited results, something like:
@AfterDataLoaded
List<Widget> loadLast20WidgetsWidgets(){
// Do query here
}
Does this annotation or pattern exist?
Upvotes: 0
Views: 889
Reputation: 23226
You can achieve this using the Hibernate specific, non JPA compliant @Where
annotation which takes a native sql clause to limit the results loaded to an associated collection.
How this query would look will depend on your database support for LIMIT, TOP etc.
@OneToMany(mappedBy = "widget", fetch = FetchType.EAGER, cascade = {})
@OrderBy("happenedDate DESC")
@Where(clause = "id in (select top 20 id from table_name order by some_field desc)")
public List<Widget> getLast20Widgets() {
return widgets;
}
Upvotes: 1
Reputation: 2652
You can use a combination of @EntityListener (class level) and @PostLoad (method level) to achieve your goal.
Upvotes: 2
Reputation: 1967
Its not possible since JPA/Hibernate has to manage entire collection's transition
say from persistent
to removed
state.
You can anyways use below alternatives:
1.HQL or Native SQL
2.Criteria Query
Upvotes: 0
Reputation: 5919
There is no annotation to limit the no of records fetched. To accomplish that, you will have to run a JPA query, and that would be trivial.
Upvotes: 0