目前项目在使用 spring boot +spring data jpa + postgresql 做项目,在项目中发现排序 按照时间排序 空指总在前,
然后上网查了查,发现在数据库中 postgresql 要这样排序:
具体博客 :https://yq.aliyun.com/articles/241219
-- 表示null排在有值行的前面
select * from tbl order by id nulls first;
-- 表示null排在有值行的后面
select * from tbl order by id nulls last;
在spring data jpa 中 ,java 是要这样写:
List<Order> orders = new ArrayList<Order>();
orders.add(new Order(Direction.DESC, "points"));
//THIS
orders.add(new Order(Direction.DESC, "person.date", NullHandling.NULLS_LAST));
//OR THIS
orders.add(new Order(Direction.DESC, "person.date").nullsLast());
//NOT WORKING
orders.add(new Order(Direction.DESC, "id"));
List<Foo> foos = fooRepository.findAll(new Sort(orders));
然而很遗憾,这样试过后 发现不起作用。
最后 翻墙 发现 可以这样:
在spring boot YML 文件中 可以这样设置:
spring:
jpa:
properties:
hibernate.order_by.default_null_ordering: last
# or for first: hibernate.order_by.default_null_ordering: first
PS: 这样做得后果就是 一旦排序 都会默认 跟你 把 null 值 排在前或者后 ,无法定制化。如果有解决得高人 请评论下 或者私信下 ,万分感谢 ^^