使用 jOOQ 3.14 中的嵌入式
jOOQ 3.14 推出“可嵌入类型” https://www.jooq.org/doc/latest/manual/code-generation/codegen-embeddable-types/,在代码生成器的基础上彻底解决了这个问题。您可以像这样定义一个嵌入:
<configuration>
<generator>
<database>
<embeddables>
<embeddable>
<name>APPROVAL_INFORMATION</name>
<fields>
<field><expression>APPROVER</expression></field>
<field><expression>APPROVED_AT</expression></field>
</fields>
</embeddable>
</embeddables>
</database>
</generator>
</configuration>
(可以进行更具体的配置,详细信息请参阅手册 https://www.jooq.org/doc/latest/manual/code-generation/codegen-embeddable-types/)。现在这将生成一个辅助EmbeddableRecord
为您提供以下形式:
public class ApprovalInformationRecord
extends EmbeddableRecordImpl<ApprovalInformationRecord> {
public ApprovalInformationRecord(
String approver, LocalDateTime approvedAt
) { /* ... */ }
// Getters, setters
}
您可以在查询、投影等中使用此嵌入项代替基础列。
Result<Record2<Long, ApprovalInformationRecord>> result =
ctx.select(T.ID, T.APPROVAL_INFORMATION)
.from(T)
.where(T.APPROVAL_INFORMATION.eq(new ApprovalInformationRecord(...))
.fetch();
使用自定义接口的通用解决方案
您可以轻松配置和扩展 jOOQ 代码生成器来为您添加类型信息。由于您想要处理生成的记录,只需将如下所示的新接口添加到您的代码库中:
public interface Approvable {
void setApprover(String approver);
void setApprovedAt(Timestamp approvedAt);
}
然后配置代码生成器,让所有相关的生成记录使用生成器策略实现上述接口:
- 程序化 https://www.jooq.org/doc/latest/manual/code-generation/codegen-generatorstrategy/
- 配置性 https://www.jooq.org/doc/latest/manual/code-generation/codegen-matcherstrategy/
一个配置示例:
..
<generator>
<strategy>
<matchers>
<tables>
<table>
<expression>MY_TABLE</expression>
<recordImplements>com.example.Approvable</recordImplements>
</table>
</tables>
</matchers>
</strategy>
</generator>