JOOQ 初始化 DAO 最佳方法

JOOQ initializing DAO Best Approach

我想知道初始化 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<String> 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 是一个非常轻量级的对象。包装 Connection.

Configuration 也是如此

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

但这是一个小风险,而且很容易解决:

使用依赖注入来管理 DAOConfiguration 引用

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

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);
         }
    }
}