jpql @query大小写

时间:2019-01-06 11:22:44

标签: jpa jpql

我正在JPQL中实现搜索方法,该方法从类的两个字段中的给定参数中搜索Institution类的所有对象。如果没有对象,则应返回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);

2 个答案:

答案 0 :(得分:0)

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?

答案 1 :(得分:0)

感谢您的建议Simon :)。我发现了一个错误。在服务类层中,我忘记了检查是否有空白字符。因此,控制器将返回从数据库转换为dto的整个List。第一个解决方案是正确的。它只要求这样:

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