JOOQ初始化DAO最佳方法

我想知道初始化JOOQ生成的DAO的最佳实践。 现在,我正在使用以下方法来启动JOOQ生成的DAO。 在以下情况中,StudentDao是JOOQ生成的。

public class ExtendedStudentDAO extends StudentDao { public ExtendedStudentDAO () { super(); } public ExtendedStudentDAO (Connection connection) { Configuration configuration = DSL.using(connection, JDBCUtils.dialect(connection)).configuration(); this.setConfiguration(configuration); } //adding extra methods to DAO using DSL public String getStudentName(Long ID) throws SQLException { try (Connection connection = ServiceConnectionManager.getConnection()) { DSLContext dslContext = ServiceConnectionManager .getDSLContext(connection); Record1 record = dslContext .select(Student.Name) .from(Student.Student) .where(Student.ID .equal(ID)).fetchOne(); if (record != null) { return record.getValue(Student.Name); } return null; } } } 

我怀疑使用上面的DAO我的示例代码如下。

 try (Connection connection = ServiceConnectionManager.getConnection()) { ExtendedStudentDAO extendedStudentDAO =new ExtendedStudentDAO(connection); Student stud=new Student(); ..... .... //insert method is from Generated DAO extendedStudentDAO.insert(stud); //this method is added in extended class extendedStudentDAO.getStudentName(12); } 

有两种方法可以看待这种初始化:

每次需要时创建DAO

你的方法是正确的,但可能会被认为有点沉重。 您每次需要时都会创建一个新的DAO

从jOOQ 3.7开始, DAO是一个非常轻量级的对象。 包装ConnectionConfiguration也是如此。

一旦您的项目发展(或在未来的jOOQ版本中),这可能不再适用,因为您的Configuration初始化(或jOOQ的DAO初始化)可能会变得更重。

但这是一个小风险,并且很容易修复:

使用dependency injection来管理DAOConfiguration引用

大多数人只为他们的应用程序设置一个jOOQ Configuration ,并且在服务中的某个地方只设置一个DAO实例(每个DAO类型)。 在这种情况下,您的Configuration不得共享Connection引用,而是通过ConnectionProvider SPI提供与jOOQ的ConnectionProvider 。 在你的情况下,这似乎微不足道:

 class MyConnectionProvider implements ConnectionProvider { @Override public Connection acquire() { return ServiceConnectionManager.getConnection(); } @Override public void release(Connection connection) { try { connection.close(); } catch (SQLException e) { throw new DataAccessException("Error while closing", e); } } }