Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: Sorting a list without 'touching' the database

Tags:

java

hibernate

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?

like image 438
digiarnie Avatar asked Feb 27 '23 02:02

digiarnie


1 Answers

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. You can do it even after closing the session/transaction. In this case, you don't need an active transaction; but this could mean sorting partial data, because most of the time we don't fetch complete thing -- for performance reasons. In your case, it seems something has changed in the midst. However, try sorting it after closing the transaction.

like image 150
Adeel Ansari Avatar answered Mar 07 '23 01:03

Adeel Ansari