【问题标题】:jpql @query case whenjpql @query case when
【发布时间】:2019-01-06 11:22:44
【问题描述】:

我正在 JPQL 中实现搜索方法,该方法从类的两个字段中的给定参数搜索机构类的所有对象。如果没有对象,它应该返回 null。此代码有效,但返回空集合而不是 null。

@Query("select  i from Institution i where i.city like concat('%', :pattern, '%') or " +
        "i.name like concat('%', :pattern, '%') ")
List<Institution> findAll(@Param("pattern") String criteria);

因此尝试了这种似乎有效的方法,但事实并非如此。

  @Query("select case when((i.city like concat('%', :pattern, '%')) or (i.name like concat('%', :pattern, '%' )) ) " +
        "then i else null END " +
        "from Institution i")
List<Institution> findAll(@Param("pattern") String criteria);

【问题讨论】:

  • 为什么要在select子句中做条件,而不是在where子句中?
  • 对不起,我忘了第一种方法

标签: jpa jpql


【解决方案1】:

JPA 总是返回空集合。 Spring Data JPA 正在调用 query.getResultList()

getResultList
java.util.List getResultList()
Execute a SELECT query and return the query results as an untyped List.
Returns:
a list of the results
Throws:
IllegalStateException - if called for a Java Persistence query language UPDATE or DELETE statement
QueryTimeoutException - if the query execution exceeds the query timeout value set and only the statement is rolled back
TransactionRequiredException - if a lock mode has been set and there is no transaction
PessimisticLockException - if pessimistic locking fails and the transaction is rolled back
LockTimeoutException - if pessimistic locking fails and only the statement is rolled back
PersistenceException - if the query execution exceeds the query timeout value set and the transaction is rolled back

如果返回类型是集合,则返回 null 是不好的做法,因为您的方法的使用者假定在没有元素的情况下该集合为空。

那你为什么要返回null呢?

【讨论】:

    【解决方案2】:

    感谢西蒙的建议 :) 。我发现了一个错误。在服务类层中,我忘记检查是否有空白字符。所以控制器正在返回从数据库转换为 dto 的整个列表。第一个解决方法是正确的。它只要求这个:

     public List<InstitutionDTO> findAll(String criteria) {
       if(criteria.trim().length() == 0) {
           throw new InstitutionSearchNotFoundException();
       }  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 2017-04-11
      • 2017-12-01
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 2020-01-10
      相关资源
      最近更新 更多