Hibernate is difficult for string_agg, or sorting by a nested collection

Anatoly Danilov
CodeX
Published in
3 min readJun 13, 2022

--

There are several hacks and almost no use cases when you need them.

Sorted birds

What we will cover here:

1. Setup a use case for sorting by a nested collection
2. Present a problem
3. Show how to do that in a native SQL
4. Show how to use HQL as a solution
5. Conclude the story

Use case: Students with assigned courses

Where there is an admin which for any reason wants to sort all students by their courses combined in a column.

And not only the courses themselves have to be sorted in the column, we have to make sure we keep sorting across students based on that sort 😞. Requirements are crazy these days.

The model will be pretty simple for the exercise:

Student without a course like a cowboy without a horse

Problem — no out of the box support from hibernate

You can try sorting by hibernate magic, without much success, because it won’t aggregate courses for you

The failure is obvious if you look into generated sql. It is a very basic sorting without taling into account all the other courses

Native SQL approach

First of all we have to make sure the courses themselves are sorted

Not what we want

We can achieve what we are looking for with a native SQL above but that leaves no benefits of Hibernate per se.

But it works 🤔 Let’s ship it.

Approach with Spring Data (or Hibernate?)

First of all, we need to register custom function for Hibernate to enable aggregations and internal sorting (see the ORDER BY ?3 trick)

Don’t forget to enable this dialiect in application.properties as `spring.jpa.properties.hibernate.dialect=com.example.hibernatefun.PostgresRichDialect`

Now we can compose a query on almost plain query language with aggregations which gives us exactly what we were looking for:

The usage is straightforward with the method call and default sort calls:

code sample
Long expected result

Conclusion — do not use hibernate or any ORMs, stick to a dead simple jdbc. But if are interested in trying out the above code in action, go to tests section in the repo https://github.com/anatolyD/hibernate-aggs

--

--

Anatoly Danilov
CodeX

Backend developer, not an AI/ML, boring backend developer