使用QueryDSL使用值对象(VO)进行数学运算

时间:2014-11-12 18:08:07

标签: querydsl

我正在尝试利用QueryDSL功能执行某些操作,而我仍然使用来自我的数据库的信息创建某个DTO的List,这样做我可以避免之后的混乱操作。下面的例子是我想要实现的愚蠢代表:

public class Product {
   private Quantity total;

   //more code here
}

public class Quantity {
   //code here
   public Quantity multiply(Quantity quantity) {
      return Quantity.of(this.value.multiply(quantity.numberValue());
   }
   //more code here
}



public static Function<JPQLQuery, List<MyDTO>> someMethod() {
   return q -> {

       //some code here

       q.from(...)

       //more code here

       .list(new QMyDTO(qProduct.total.multiply(qProduct.total).sum()));
   };
}

问题是QueryDSL使用NumberExpression来提供一些操作,如sum,multiply等,它适用于像BigDecimal这样的类型,但不适用于像我的值对象这样的自定义类型Quantity。我试图拿出一些东西,但我没有任何成功,我没有找到类似的东西。

是否有任何可以帮助我实现的目标?

1 个答案:

答案 0 :(得分:1)

您可以为此案例创建委托方法

@QueryDelegate(Quantity.class)
public static Expression<Quantity> multiply(QQuantity quantity, Quantity other){
    return Expressions.operation(Quantity.class,
        Ops.MULTI, quantity, ConstantImpl.create(other));
}

之后你就可以表达

qProduct.total.multiply(qProduct.total)
相关问题