Hibernate空参数本机查询Spring Boot

时间:2018-09-25 14:55:26

标签: spring postgresql hibernate spring-boot

我试图在Spring Boot中将null参数(:searchQuery)传递给本机查询,我尝试了各种不同的方法,但是每当传递null时,我都会得到错误

  

错误:运算符不存在:文本~~ bytea

查询

@Query(value = "SELECT count(*) FROM analysis_history ah, analysis_group ag WHERE ah.analysis_group_id = ag.id "
+ "AND ah.creation_date BETWEEN :from AND :to AND ((:searchQuery IS NULL) OR (:searchQuery IS NOT NULL AND ag.name LIKE :searchQuery))", nativeQuery = true)
Long count(@Param("from") Date from, @Param("to") Date to, @Param("searchQuery") String searchQuery);

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

您不能使用like null

SELECT count(*) FROM analysis_history ah, analysis_group ag 
WHERE ah.analysis_group_id = ag.id AND ah.creation_date 
BETWEEN :from AND :to AND ag.name LIKE :searchQuery

当searchQuery参数为null时,您在searchQuery中传递了'%'吗?例如

repository.count(from, to, searchQuery == null ? "%" : searchQuery);

答案 1 :(得分:0)

有一种方法可以绕过此操作,但是您需要访问EntityManager,而不要使用@Query批注为您创建该实现。

Long count(Date from,Date to, String searchQuery) {
    Number n = em.createNativeQuery("... that query")
            .setParameter("from", from, TemporalType.DATE) // assuming that's a Date, and not TimeStamp
            .setParameter("to", to, TemporalType.DATE)
            .setParameter("searchQuery", "")
            .setParameter("searchQuery", searchQuery)
            .getSingleResult();
    return n.longValue();
}

第一次调用.setParameter("searchQuery", "")会告诉Hibernate这是什么类型,下一个将设置值。

问题出在Postgres在解析过程中进行类型检查,而不是在参数集为空的情况下推迟错误。

答案 2 :(得分:0)

@coladict提出的问题的替代解决方法,它与Query兼容并且性能与原始版本相同。

SELECT count(*)
FROM analysis_history ah, analysis_group ag 
WHERE ah.analysis_group_id = ag.id 
AND ah.creation_date BETWEEN :from AND :to 
AND (:searchQuery IS NULL OR ag.name LIKE CAST(:searchQuery AS CHARACTER VARYING))