开发者

How to create constant numeric value expression in QueryDSL?

开发者 https://www.devze.com 2023-04-11 11:48 出处:网络
I\'d like to create query like this with QueryDSL update WorkMessage w set w.totalPrice = 0.12 - w.totalCost;

I'd like to create query like this with QueryDSL

update WorkMessage w set w.totalPrice = 0.12 - w.totalCost;

I tried like this

    Expression<Float> priceExpr = Expressions.constant(0.12f);

    new JPAUpdateClause(em, w)
            .set(w.totalPrice , priceExpr.subtract(开发者_Python百科w.totalCost));

But this doesn't work - Expression doesn't have subtract method.

I did it like this:

        new JPAUpdateClause(em, w)
            .set(w.totalPrice , w.totalCost.subtract(0.12f).negate());

but I'd like to know how to do it the first way.

//EDit

The second way don't work:

JPAUpdateClause.toString says:

update WorkMessage workMessage 
set workMessage.totalPrice = -(workMessage.totalCost - :a1)

but the SQL result is

update work_message set total_price=-total_cost-?

Parentheses just dissapeared. Am I doing something wrong? It looks like theese:

w.totalCost.subtract(0.12f).negate()
w.totalCost.negate().subtract(0.12f)

have the same result.

For the above problem

w.totalCost.negate().add(0.12f)

works. But I think there is a bug.


We removed the DSL Constant types some time ago from Querydsl. If you really want to write it the first way, then you have to express it like this :

Expressions.operation(Float.class, Ops.SUB, 
    Expressions.constant(0.12f), w.totalCost)

or

NumberOperation.create(Float.class, Ops.SUB, 
    Expressions.constant(0.12f), w.totalCost)

if you need a NumberExpression


I had the same problem some time ago (needed the constant 0), and did build my own ConstantNumberExpression class. It turned out surprisingly easy :-)

A collegue just had the same problem, for the constant 1, so I decided to post it here.

private static class ConstantNumberExpression extends NumberExpression<Integer> {
    private static final long serialVersionUID = 1220768215234001828L;

    public ConstantNumberExpression(final int constant) {
        super(new ConstantImpl<>(constant));
    }

    @Override
    @Nullable
    public <R, C> R accept(final Visitor<R, C> v, @Nullable final C context) {
        return v.visit((Constant<Integer>) mixin, context);
    }
}

Of course this could be done a bit more generic, using a type parameter, but we did need it only for Integer (actually only for zero and one).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号