JOOQ: Update column values on null values

走远了吗. 提交于 2019-12-24 09:18:48

问题


I need to update the value of an integer column associated with a row using JOOQ on Java. In case the value of the column is not NULL I am aware that I could use this code:

context.update(TABLENAME)
    .set(TABLENAME.COUNTER, TABLENAME.COUNTER.add(incrementValue))
    .where(TABLENAME.ID.eq(id))
    .execute();

however if the column value has NULL value I am wondering whether I could do something like the following by setting a default value in presence of NULL:

context.update(TABLENAME)
    .set(TABLENAME.COUNTER, TABLENAME.COUNTER == null ? 0 : TABLENAME.COUNTER.add(incrementValue))
    .where(TABLENAME.ID.eq(id))
    .execute();

Is it possible? How should I perform it?

Thanks a lot!


回答1:


Why doesn't your approach work?

jOOQ does not translate arbitrary Java expressions to SQL. I.e. your TABLENAME.COUNTER == null check is evaluated in Java prior to passing the expression to jOOQ. It will never be generated in SQL. And since TABLENAME.COUNTER, being generated code, will never be null, the conditional expression is really meaningless.

Solutions

You could use DSL.coalesce() or DSL.nvl() or DSL.ifnull()

.set(TABLENAME.COUNTER, coalesce(TABLENAME.COUNTER, inline(-1)).add(incrementValue))

There's also the Oracle style DSL.nvl2() function you could use:

.set(TABLENAME.COUNTER, 
     nvl2(TABLENAME.COUNTER, TABLENAME.COUNTER.add(incrementValue), inline(0)))

Alternatively, write a CASE expression

.set(TABLENAME.COUNTER, 
     when(TABLENAME.COUNTER.isNull(), inline(0))
     .otherwise(TABLENAME.COUNTER.add(incrementValue)))

As always, the above is assuming you have the following static import:

import static org.jooq.impl.DSL.*;


来源:https://stackoverflow.com/questions/52334114/jooq-update-column-values-on-null-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!