【问题标题】:JOOQ initializing DAO Best ApproachJOOQ 初始化 DAO 最佳方法
【发布时间】:2016-03-17 16:08:09
【问题描述】:

我想知道初始化 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);

}

【问题讨论】:

    标签: java sql jooq vert.x


    【解决方案1】:

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

    每次需要时创建 DAO

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

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

    一旦您的项目发展(或在未来的 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);
             }
        }
    }
    

    【讨论】:

    • 如果您打算在事务中使用 DAO 怎么办?您是否应该使用事务的范围配置来实例化 DAO?还是没关系
    • @NayeemZen 如果您使用 jOOQ 的事务 API,那么是的,您必须使用作用域配置实例化 DAO。如果您使用 Spring 的事务 API(它是线程绑定的),那么您不需要实例化单独的 DAO。如有疑问,请随时提出新问题,我会解释。
    猜你喜欢
    • 2018-03-09
    • 2014-02-22
    • 2011-11-24
    • 1970-01-01
    • 2015-07-16
    • 2015-12-02
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多