簡體   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