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

╄→尐↘猪︶ㄣ 提交于 2019-12-12 12:26:13

问题


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");

回答1:


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.



来源:https://stackoverflow.com/questions/32749409/spring-data-and-how-to-sort-by-a-column-not-in-an-entity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!