我正在使用JOOQ为我的数据库表生成pojos。这很棒。
我有一个带有主键(identifier
)和唯一键(name
)的表。更新记录时,JOOQ使用主键。
我想使用唯一键而不是主键更新记录。
https://github.com/jooq/jooq/blob/master/jooq/src/src/main/java/jooq/jooq/impl/updatablerecordimpl.java
@Override
public final int update() {
return update(fields.fields.fields);
}
@Override
public int update(Field<?>... storeFields) throws DataAccessException, DataChangedException {
return storeUpdate(storeFields, getPrimaryKey().getFieldsArray());
}
本质上,我想用另一个键(第二参数)调用storeUpdate
。我尝试扩展生成的记录,但storeUpdate
是私有的。
还有另一种更新记录的方法吗?我可以在update()
之前首先选择标识符,但它引入了一个额外的查询,我想避免。
从评论中,我知道您想:
- 将生成的记录用作" ActivereCords"保存将存储/更新到表中的数据
- 使用任意"密钥"信息作为您的更新语句的选择性标准
有两种方法可以使用JOOQ:
1。覆盖代码生成器中的主要密钥信息
您可以在数据库中指定匹配唯一密钥名称的正则表达式,该名称应覆盖生成的代码中的主要键:
<!-- All (UNIQUE) key names that should be used instead of primary keys on
generated UpdatableRecords, to be used with
- UpdatableRecord.store()
- UpdatableRecord.update()
- UpdatableRecord.delete()
- UpdatableRecord.refresh()
If several keys match, a warning is emitted and the first one encountered
will be used.
This flag will also replace synthetic primary keys, if it matches. -->
<overridePrimaryKeys>MY_UNIQUE_KEY_NAME</overridePrimaryKeys>
请注意,此解决方案将影响 all 对store()
,update()
等的调用等。从您的评论中,这可能不是所需的行为...有关更多信息,请参阅JOOQ手册
2。使用常规更新语句
您可以将整个UpdatableRecord
传递给UPDATE
语句,并明确指定选择标准,例如:
MyTableRecord record = ...;
DSL.using(configuration)
.update(MY_TABLE)
.set(record)
.where(MY_TABLE.NAME.eq(record.getName())
.execute();