[英]Spring Query with optional nulls and case insensitive
I'm using Spring Boot 2.2.5.RELEASE with Java 8 and PostgreSQL and I need to retrieve some data from a table.我正在使用 Spring Boot 2.2.5.RELEASE 和 Java 8 和 PostgreSQL,我需要从表中检索一些数据。 To do that I can receive some optional values and they need to be case sensitive (mostly because some of them are Hex Strings).
为此,我可以接收一些可选值,它们需要区分大小写(主要是因为其中一些是十六进制字符串)。 To handle that I'm using a CRUD repository with a query like the example bellow:
为了处理这个问题,我使用了一个带有查询的 CRUD 存储库,如下例所示:
@Repository
public interface MyRepository extends CrudRepository<MyStuff, String> {
@Query("SELECT s FROM Stuff s WHERE (:name is null or upper(s.name) = upper(:name)) "
+ "and (:age is null or upper(s.age) = upper(:age)) "
+ "and (:status is null or upper(s.status) = upper(:status))")
List<MyStuff> findStuff(@Param("name") String name,
@Param("age") String age,
@Param("status") String status);
I've removed some information to make it clear, but the gist of it is there.我已经删除了一些信息以使其清楚,但它的要点就在那里。 The problem is, only one field must have a value, the others can be null.
问题是,只有一个字段必须有值,其他字段可以是 null。 It should be simple enough, because I'm checking for null before casting the fields to upper case, but when I try to run it I get an error because the null values are being interpreted as
bytea
and so there is no method to change its case.它应该很简单,因为我在将字段转换为大写之前检查了 null,但是当我尝试运行它时出现错误,因为 null 值被解释为
bytea
,因此没有方法可以更改其案子。 How can I handle it without having a method in java to check for nulls and change to upper case on Java side?如果没有 java 中的方法来检查空值并在 Java 端更改为大写,我该如何处理它?
I wouldn't recommend that you do that.我不建议你这样做。 A DBMS will use a pretty conservative query plan when encountering something like that.
遇到类似情况时,DBMS 将使用相当保守的查询计划。 You should use Spring-Data Specifications for conditional filters like this.
对于这样的条件过滤器,您应该使用 Spring-Data 规范。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.