英文:
How to order a stream receiving parameter in the request using spring JPA
问题
public List<BillToPay> findWithOrderBy(String orderName, String orderDir) {
List<BillToPay> listBillToPay = this.repository.findAll(Sort.by(orderDir.equals("ASC") ? Sort.Direction.ASC : Sort.Direction.DESC, orderName));
}
英文:
I need to order the stream from the parameters received above, how can I do this safely and that it works in an ASC and DESC way?
public List<BillToPay> findWithOrderBy(String orderName, String orderDir) {
List<BillToPay> listBillToPay = this.repository.findAll();
}
答案1
得分: 0
不需要为此创建流,因为Spring Data JPA已经有重载的方法允许排序。您只需要将参数转换为必要的类型,例如:
//在这里传递要按其排序的字段的名称,而不是实际值
public List<BillToPay> findWithOrderBy(String fieldName, String direction) {
Sort.Direction dir = direction.equalsIgnoreCase("asc") ? Sort.Direction.ASC
: Sort.Direction.DESC;
List<BillToPay> listBillToPay = this.repository.findAll(Sort.by(dir, fieldName));
return listBillToPay;
}
JPA方法接受一个可变的字符串参数,因此假设您想按相同方向排序多个字段(不是ASC/DESC混合),您可以轻松实现它并几乎不改变任何内容。
//方向必须首先出现,因为变量参数必须出现在签名的最后
public List<BillToPay> findWithOrderBy(String direction, String...fieldNames) {
Sort.Direction dir = direction.equalsIgnoreCase("asc") ? Sort.Direction.ASC
: Sort.Direction.DESC;
List<BillToPay> listBillToPay = this.repository.findAll(Sort.by(dir, fieldNames));
return listBillToPay;
}
英文:
You don't need a stream for this as Spring Data JPA already has overloaded methods that allow sorting. You just need to convert your arguments to the necessary type such as:
//Pass the name of the field you want to sort by here, not the actual value
public List<BillToPay> findWithOrderBy(String fieldName, String direction) {
Sort.Direction dir = direction.equalsIgnoreCase("asc") ? Sort.Direction.ASC
: Sort.Direction.DESC;
List<BillToPay> listBillToPay = this.repository.findAll(Sort.by(dir, fieldName));
return listBillToPay;
}
The JPA method accepts a variable String argument, so assuming you want to sort by multiple fields all in the same direction (not a mix of ASC/DESC) you could easily implement it and barely change anything.
//Direction needs to come first as variable parameter must come last in the signature
public List<BillToPay> findWithOrderBy(String direction, String...fieldNames) {
Sort.Direction dir = direction.equalsIgnoreCase("asc") ? Sort.Direction.ASC
: Sort.Direction.DESC;
List<BillToPay> listBillToPay = this.repository.findAll(Sort.by(dir, fieldNames));
return listBillToPay;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论