嵌入式键
适用于 ❌ 开源版 ✅ Express 版 ✅ 专业版 ✅ 企业版
可嵌入类型的一个非常有用的应用是 PRIMARY KEYS、UNIQUE 约束和 FOREIGN KEYS。通过两个非 FOREIGN KEY 及其引用的 PRIMARY / UNIQUE 键的列来连接两个表只有少数几个好的用例。如果选择了这样的两列,则主要是因为输入错误,甚至是因为误解了底层模式。
您可以像这样启用此功能
<configuration>
<generator>
<database>
<!-- Use regular expressions to match the keys that should be replaced by embeddables. -->
<embeddablePrimaryKeys>.*</embeddablePrimaryKeys>
<embeddableUniqueKeys>.*</embeddableUniqueKeys>
</database>
</generator>
</configuration>
有关更多详细信息,请参见配置 XSD、独立的代碼生成,以及maven 代码生成。
new org.jooq.meta.jaxb.Configuration()
.withGenerator(new Generator()
.withDatabase(new Database()
// Use regular expressions to match the keys that should be replaced by embeddables.
.withEmbeddablePrimaryKeys(".*")
.withEmbeddableUniqueKeys(".*")
)
)
有关更多详细信息,请参见配置 XSD和以编程方式的代码生成。
import org.jooq.meta.jaxb.*
configuration {
generator {
database {
// Use regular expressions to match the keys that should be replaced by embeddables.
embeddablePrimaryKeys = ".*"
embeddableUniqueKeys = ".*"
}
}
}
有关更多详细信息,请参见配置 XSD和gradle 代码生成。
configuration {
generator {
database {
// Use regular expressions to match the keys that should be replaced by embeddables.
embeddablePrimaryKeys = ".*"
embeddableUniqueKeys = ".*"
}
}
}
有关更多详细信息,请参见配置 XSD和gradle 代码生成。
// The jOOQ-codegen-gradle plugin has been introduced in version 3.19. // Please use the official plugin instead of the third party plugin that was recommended before.
一如既往,当使用正则表达式时,它们是具有默认标志的正则表达式。
这将自动为每个 PRIMARY KEY 和/或 UNIQUE 键,以及每个引用 PRIMARY KEY 或 UNIQUE 键的 FOREIGN KEY 生成可嵌入类型配置。 生成的配置可以手动编写,但是当键重叠时,或者当表通过关系表以传递方式引用“远程”主键时,配置生成算法并不简单。
将其应用于我们的示例数据库,以及精心设计的约束名称(生成的可嵌入对象使用约束名称),或者以编程方式生成器策略,或者配置型匹配器策略,我们可能会得到像这样的org.jooq.EmbeddableRecord类型
// Both primary and foreign key produce the respective primary key record
Result<Record5<PkBookRecord, String, PkAuthorRecord, String, String>> result =
create.select(
BOOK.PK_BOOK,
BOOK.TITLE,
BOOK.FK_BOOK_AUTHOR,
AUTHOR.FIRST_NAME,
AUTHOR.LAST_NAME)
.from(BOOK)
.join(AUTHOR)
// This join compiles
.on(BOOK.AUTHOR_ID.eq(AUTHOR.ID))
// This wrong join wouldn't compile
// .on(BOOK.LANGUAGE_ID.eq(AUTHOR.ID))
.fetch();
for (Record5<PkBookRecord, String, PkAuthorRecord, String, String> record : result) {
System.out.println("ID : " + record.value1().getId());
System.out.println("TITLE : " + record.value2());
System.out.println("AUTHOR_ID : " + record.value3().getId());
System.out.println("FIRST_NAME: " + record.value4());
System.out.println("LAST_NAME : " + record.value5());
}
请注意
- 每个主键都会生成一个可嵌入的记录类型。
- 主键和外键列都引用主键记录类型。
- 这意味着只有匹配的主/外键列才能在连接中进行比较。仅它们都属于
java.lang.Integer类型是不够的
复合键
当键是复合键时,此功能甚至更强大!您不再需要在连接谓词中列出每对连接列,只需按主/外键可嵌入类型连接即可。优点是
- 通过复合键连接时,您永远不会再忘记列
- 如果从键中添加/删除列,您永远不会忘记重构所有查询。只需重新生成 jOOQ 代码,查询就会自动更新
反馈
您对此页面有任何反馈吗?我们很乐意听取您的意见!