环境:
Spring应用程序,使用JOOQ 3.7,从模式自动生成JOOQ映射代码,使用Postgres作为我的数据库。
我已经将一些代码从 Hibernate 移植到 JOOQ。
Hibernate 代码会根据上下文提取一些隐藏的身份验证详细信息,以填充“createdBy”、“updatedBy”、日期等字段。
目前,我认为使用 JOOQ 执行此操作的唯一方法是,开发人员必须记住在每次更新对象时编写代码来手动更新字段,而且我发现这会很乏味且很容易忘记填充字段。
使用 JOOQ,有什么方法可以比手动编写一堆代码更好地处理每个表上的“历史字段”?
我们目前不使用 DAO,我宁愿避免编写/生成整个代码层来处理这些历史字段。
另一种选择可能是在数据库中执行此操作,如果 JOOQ 无法帮助解决问题,那么我们很可能会这样做。
使用 jOOQ 有多种方法可以做到这一点:
1.使用jOOQ 3.17的客户端计算列
从 jOOQ 3.17 开始,审计列和其他类型的客户端计算列可用:
-
#1592 https://github.com/jOOQ/jOOQ/issues/1592 审计专栏 https://www.jooq.org/doc/latest/manual/code-generation/codegen-advanced/codegen-config-database/codegen-database-forced-types/codegen-database-forced-types-audit/
-
#9879 https://github.com/jOOQ/jOOQ/issues/9879 客户端计算列 https://www.jooq.org/doc/latest/manual/code-generation/codegen-advanced/codegen-config-database/codegen-database-forced-types/codegen-database-forced-types-computed/
jOOQ 3.17 正是实现了此功能,以及其他一些不错的附加功能,例如二维版本控制,这可能会在未来版本中提供:
-
#4704 https://github.com/jOOQ/jOOQ/issues/4704SQL:2011 时间有效性
2. 使用RecordListener
生成这些值UpdatableRecord
The RecordListener
每次调用以下任一函数时都会调用 SPI:
- TableRecord.insert() http://www.jooq.org/javadoc/latest/org/jooq/TableRecord.html#insert--
- UpdatableRecord.store() http://www.jooq.org/javadoc/latest/org/jooq/UpdatableRecord.html#store--
- UpdatableRecord.update() http://www.jooq.org/javadoc/latest/org/jooq/UpdatableRecord.html#update--
- UpdatableRecord.delete() http://www.jooq.org/javadoc/latest/org/jooq/UpdatableRecord.html#delete--
- UpdatableRecord.refresh() http://www.jooq.org/javadoc/latest/org/jooq/UpdatableRecord.html#refresh--
但是,当您编写显式 DML 语句时,不会调用此 SPI。有关更多信息,请参阅此处的手册:
- http://www.jooq.org/doc/latest/manual/sql-execution/crud-with-updatablerecords/crud-record-listener http://www.jooq.org/doc/latest/manual/sql-execution/crud-with-updatablerecords/crud-record-listener
3. 使用VisitListener
转换jOOQ生成的所有SQL语句
The VisitListener
SPI 可用于任意 SQL 转换操作。您可以拦截 jOOQ 生成的各种 SQL 语句,并向它们添加附加子句,例如
UPDATE table SET a = 1, b = 2 WHERE id = 3
会成为
UPDATE table SET a = 1, b = 2, updatedBy = 'me' WHERE id = 3
该 SPI 记录在手册中:
- http://www.jooq.org/doc/latest/manual/sql-building/queryparts/custom-sql-transformation http://www.jooq.org/doc/latest/manual/sql-building/queryparts/custom-sql-transformation
4. 编写触发器
我认为最好的解决方案是使用触发器将此类自动生成的数据移至数据库中。这将允许您在迁移、手动更新或通过 Java 之外的其他语言(例如 Perl 脚本等)访问时更新这些值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)