简体   繁体   English

Spring Data-JPA:使用DTO和IF语句发出查询

[英]Spring data - JPA : issue query with DTO and IF statement

I am trying to make a query that would build a DTO object : 我试图做一个查询,将建立一个DTO对象:

@Query("Select new com.mycorp.rh.web.rest.dto.AnalyseProductionDTO(a.client.name, IF(a.salarie,'yes','no'))   
from Activity a where a.year = ?1 and a.month = ?2")
        List<AnalyseProductionDTO> getAnalyseProduction(Year year, Month month);

It doesn't work when I put a IF statement in the query. 当我在查询中放入IF语句时,它不起作用。
I am getting a 我正在

java.lang.IllegalArgumentException: Validation failed for query java.lang.IllegalArgumentException:查询验证失败

It works when I do : 当我这样做时它会工作:

@Query("Select new com.mycorp.rh.web.rest.dto.AnalyseProductionDTO(a.client.name, 'yes')   
from Activity a where a.year = ?1 and a.month = ?2")
        List<AnalyseProductionDTO> getAnalyseProduction(Year year, Month month);

Isn't it possible to include an IF statement in a constructor used in a query? 是否可以在查询中使用的构造函数中包含IF语句?

By default @Query doesn't allow native queries. 默认情况下, @Query不允许本机查询。 The query should be either HQL if the ORM is hibernate or anything that is supported by the underlying ORM. 如果ORM处于休眠状态,则查询应为HQL或基础ORM支持的任何查询。

Since IF() function is native to MySQL and not supported by ORM query languages its validation will fail. 由于IF()函数是MySQL固有的,并且不受ORM查询语言支持,因此其验证将失败。

You can try the following with @Query.nativeQuery set to true . 您可以将@Query.nativeQuery设置为true来尝试以下操作。

@Query(value = "Select new com.mycorp.rh.web.rest.dto.AnalyseProductionDTO(a.client.name, IF(a.salarie,'yes','no'))   
from Activity a where a.year = ?1 and a.month = ?2", nativeQuery = true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM