mikeb
mikeb

Reputation: 11267

JPA 2.1 Load extra data after object is loaded

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

Answers (4)

Alan Hay
Alan Hay

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.

https://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-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

Sanjeev Saha
Sanjeev Saha

Reputation: 2652

You can use a combination of @EntityListener (class level) and @PostLoad (method level) to achieve your goal.

Upvotes: 2

shankarsh15
shankarsh15

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

Pradeep Pati
Pradeep Pati

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

Related Questions