当值不为空时更新列 JOOQ

Update a column when value is not null JOOQ

我只想在收到的 POJO 中的给定值不为空时更新列。

我想实现这个SQL:

Update TABLE table_name SET column_name = COALESCE(value, column_name)

这是我在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();
    }

在你做的更新语句中

coalesce(<input_value>, column_name)

但是在 jOOQ 查询中你这样做

coalesce(column_name, <input_value>)

所以你应该改变顺序

 public int updateCompany(final Company company) {

    return dslContext.update(COMPANY)
            .set(COMPANY.REGISTERED_NAME, company.getRegisteredName())
            .set(COMPANY.TRADING_NAME, coalesce(company.getTradingName(), COMPANY.TRADING_NAME))
            .set(COMPANY.ADDRESS_ID, coalesce(company.getAddressId(), COMPANY.ADDRESS_ID))
            .where(COMPANY.ID.eq(company.getId()))
            .execute();
}

除了 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

的bug

同时,您必须使用 DSL.val(), see the manual section about bind values.

明确包装您的绑定值

例如

.set(COMPANY.TRADING_NAME, coalesce(val(company.getTradingName()), COMPANY.TRADING_NAME)
.set(COMPANY.ADDRESS_ID, coalesce(val(company.getAddressId()), COMPANY.ADDRESS_ID))

或者,使用等效的 2-argument DSL.nvl(T, Field<T>) function,它没有此限制,因为它没有可变参数。