I want to update a column only when the given value is not null in the POJO I am receiving.
I want to implement this SQL:
Update TABLE table_name SET column_name = COALESCE(value, column_name)
Here is the function I have written in JOOQ
public int updateCompany(final Company company) {
return dslContext.update(COMPANY)
.set(COMPANY.REGISTERED_NAME, company.getRegisteredName())
.set(COMPANY.TRADING_NAME, coalesce(COMPANY.TRADING_NAME, company.getTradingName()))
.set(COMPANY.ADDRESS_ID, coalesce(COMPANY.ADDRESS_ID, company.getAddressId()))
.where(COMPANY.ID.eq(company.getId()))
.execute();
}
In addition to the bug that Simon Martinelli found, the problem here is that there's no overload DSL.coalesce(T, Field<T>...)
, which your code is assuming there is. Not unreasonably so, there's usually such an overload. In this case, there isn't for historic reasons. In Java 6, there was no @SafeVarargs
yet, and jOOQ 3.14 still supports Java 6. With jOOQ 3.15 no longer supporting Java 6, this could be fixed. I've created an issue for this: https://github.com/jOOQ/jOOQ/issues/11690
In the meantime, you have to explicitly wrap your bind value using DSL.val()
, see the manual section about bind values.
E.g.
.set(COMPANY.TRADING_NAME, coalesce(val(company.getTradingName()), COMPANY.TRADING_NAME)
.set(COMPANY.ADDRESS_ID, coalesce(val(company.getAddressId()), COMPANY.ADDRESS_ID))
Alternatively, use the equivalent 2-argument DSL.nvl(T, Field<T>)
function, which doesn't have this limitation as it doesn't have a varargs parameter.