一光年

[Spring-JPA] 无条件查询OrderBy的写法

2019.06.13

在JPA查询中如果有排序的需求,一般写作:

  ...
  // User按性别进行降序排列
  userRepository.findAllByGenderOrderByCreateAtDesc(Gender.MALE);  
  ...

如果不需要按性别查询直接排序,第一反应想到的是把ByGender去掉:

  ...
  userRepository.findAllOrderByCreateAtDesc();
  ...

然后应用启动时会直接报错。

正确的写法是,在findAll后面仍然加上By关键字:

  ...
  userRepository.findAllByOrderByCreateAtDesc();
  ...

看JPA的源码,在PartTree中有以下的模板定义:

package org.springframework.data.repository.query.parser;
...
public class PartTree implements Streamable<OrPart> {

  private static final String KEYWORD_TEMPLATE = "(%s)(?=(\\p{Lu}|\\P{InBASIC_LATIN}))";
	private static final String QUERY_PATTERN = "find|read|get|query|stream";
	private static final String COUNT_PATTERN = "count";
	private static final String EXISTS_PATTERN = "exists";
	private static final String DELETE_PATTERN = "delete|remove";
	private static final Pattern PREFIX_TEMPLATE = Pattern.compile( //
			"^(" + QUERY_PATTERN + "|" + COUNT_PATTERN + "|" + EXISTS_PATTERN + "|" + DELETE_PATTERN + ")((\\p{Lu}.*?))??By");
}
...

看得出来,By作为模板关键字的末尾,是必写的内容。