tags:

views:

43

answers:

1

I've got a many-to-many relationship in my database and I'm using Hibernate to retrieve a single row from the left hand side of the relationship. I then just call the getter method to retrieve the associated right hand side of the relationship (lazy fetch).

As part of my work, I need to sort the right hand side "list" object by doing this:

Collections.sort(list);

When I'm done my work, I'm currently calling:

session.getTransaction().commitTransaction();

Even though I haven't actually changed anything in the database in terms of the data, I can see in the logs that some INSERT statements were triggered.

What should I be doing in this situation so that I could order the list without incurring a database hit?

+3  A: 

There are few ways to do it.

First, you can use @OrderBy annotation on your collection definition. Refer to the link here. In this way, Hibernate will append the query with order by clause.

Second, if you are using Criteria API to query the DB, you can use addOrder() method to add the order by clause.

Third, you can directly use order by clause in your HQL.

Fourth, you can do it in your code, using Comparator. In this case, you don't need an active transaction. You can do it even after closing the session/transaction. In your case, it seems something has changed in the midst. However, try sorting it after the closing the transaction.

Adeel Ansari
The @OrderBy annotation did the trick. Thanks!
digiarnie
@digiarnie: Anytime. Glad it solves the issue.
Adeel Ansari