繁体   English   中英

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是一个非常轻量级的对象。 包装ConnectionConfiguration也是如此。

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM