Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data and how to sort by a column not in an Entity

I'm new to Java Spring and trying to understand how it works as I go. My goal here is to apply a sort to a JPQL query that is not in an Entity.

References I've been looking at:

Spring Sort Class Docs

Spring Sort crash course

If I declare the following query

@Query("SELECT a, b.someColumn FROM TableA a INNER JOIN a.tableB b where a.search like %?1%"
public Page<Object[]> findSomething(String search, Pageable pageable);

This will result in a list of objects with a form of

Object[0] = TableA entity
Object[1] = b.someColumn value

I've been reading up on the Sort class, but I haven't found a way to make this sort by b.someColumn.

If I do the following

Sort sort = new Sort(Sort.Direction.DESC, "someColumn");
Page<Object[]> things = mgr.findSomething("junk", sort);

Then the JPQL results in

SELECT a, b.someColumn FROM TableA a INNER JOIN a.tableB b where a.search like ?1 order by a.someColumn

when I want it to be

SELECT a, b.someColumn FROM TableA a INNER JOIN a.tableB b where a.search like ?1 order by b.someColumn

How do I prevent it from appending the sort column to the Entity in the query? Is there a way to disable this function and make it interpret my sort column literally? Is there a better sorting technique that would be more appropriate to my case?

Sort sort = new Sort(Sort.Direction.DESC, "b.someColumn");
like image 613
Kevin Avatar asked Sep 23 '15 21:09

Kevin


1 Answers

Well, it looks like I answered my own question in my original question. For some reason my browser wasn't up to date with my recent changes and I didn't see the sort working.

The engine will interpret sort columns literally.

Sort sort = new Sort(Sort.Direction.DESC, "b.someColumn");

Will result in

SELECT a, b.someColumn FROM TableA a INNER JOIN a.tableB b where a.search like ?1 order by b.someColumn

Which is exactly what I wanted.

like image 99
Kevin Avatar answered Oct 10 '22 17:10

Kevin