JOOQ:在空值上更新列值

编程入门 行业动态 更新时间:2024-10-27 21:22:55
本文介绍了JOOQ:在空值上更新列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要在Java上使用JOOQ更新与行关联的整数列的值.如果该列的值不为NULL,我知道我可以使用以下代码:

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();

但是,如果列值具有NULL值,我想知道是否可以通过在存在NULL的情况下设置默认值来执行以下操作:

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?

非常感谢!

推荐答案

您的方法为什么行不通?

jOOQ不会将任意Java表达式转换为SQL. IE.在将表达式传递给jOOQ之前,将使用Java对您的TABLENAME.COUNTER == null检查进行评估.它永远不会在SQL中生成.而且由于TABLENAME.COUNTER作为生成的代码将永远不会是null,因此条件表达式实际上是毫无意义的.

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.

您可以使用 DSL.coalesce() 或 DSL.nvl() 或 DSL.ifnull()

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

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

还有Oracle风格 DSL.nvl2() 您可以使用的函数:

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

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

或者,编写一个> 表达式

.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.*;

更多推荐

JOOQ:在空值上更新列值

本文发布于:2023-10-20 09:15:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1510555.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JOOQ   空值上

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!