使用MathExpressions.round时生成的SQL查询不一致

时间:2016-05-12 14:37:03

标签: sql querydsl

我正在尝试创建一个查询,我需要在一个选定的字段中添加舍入(设置小数位1)。

这是我的代码:

JPAQuery query = new JPAQuery(em);              
QMyEntity myEntity = QMyEntity.myEntity;        
QSecondaryEntity secondaryEntity = QSecondaryEntity.secondaryEntity;    

Expression<String> idExpression= (new CaseBuilder()
            .when(myEntity.type.eq(4)).then(myEntity.normalId)
            .otherwise(myEntity.specialId)).as("id");

NumberExpression<BigDecimal> roundExpression = MathExpressions.round(myEntity.qty, 1).as("roundedQty");

query = query.from(browse, lips).where(predicate);

return query.list(Projections.constructor(MyEntityDto.class, myEntity.field1, myEntity.field2, roundExpression, idExpression));

MyEntity不直接映射名为“MyEntity”的数据库表,而是“Table0”。

当我看到生成的查询时,我看到:

select myEntity.field1, myEntity.field2, round(myEntity.qty),
       (case when (myEntity.type = ?1) then myEntity.normalId
                                       else myEntity.specialId end) as id
from MyEntity myEntity
where myEntity.id = ?2 and ... 

我收到了这个错误:

  

SELECT子句有'round'和'(myEntity.qty)'不是   用逗号隔开。

然而,如果我删除圆形表达式,生成的查询就可以了,并查询数据库中的正确表格:

SELECT t1.Field1 AS a1, t0.Field2 AS a2, t0.Quantity AS a3,
       CASE  WHEN (t0.Type = ?) THEN t3.ID ELSE t3.SecondID END 
FROM Table7 t7, Table t6,..., Table1 t1, Table0 t0 
WHERE ((((((((t ...

我正确使用MathExpression吗?在select子句中舍入字段的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

我认为这是一个库bug。如果您尝试执行相同的查询,则不要放置&#39; round&#39;引号也会失败:

Expression round = TemplateExpressionImpl.create(BigDecimal.class, "'round(myEntity.qty, 1)' as roundedQty");

Expression round2 = TemplateExpressionImpl.create(BigDecimal.class, "'round({0}, {1})' as roundedQty", myEntity.qty, 1);

您可以尝试使用createQuery,但必须指出完整的查询:

Query q = em.createQuery("SELECT round(myEntity.qty, 1) FROM MyEntity myEntity WHERE ....");

它也失败了,但是使用createQuery你可以放置引号并且它可以工作:

Query q = em.createQuery("SELECT 'round(myEntity.qty, 1)' FROM MyEntity myEntity WHERE ....");