2015-08-31 48 views
0

我有一個DAO,(稱之爲PlayerDao)具有下列方法:DAO可以使用一個本身封裝一個dataSource對象的對象嗎?

public interface PlayerDao{ 
    //Other methods 
    public Collection<Integer> getPlayerRegisteredIds(); 
} 

現在我需要提供兩個實施該方法:

。直接類似下面的數據源執行SELECT查詢:

public class PlayerDaoImpl implements PlayerDao{ 

    private DataSource dataSource; //javax.sql.DataSource 
    //Other methods 
    public Collection<Integer> getPlayerRegisteredIds(){ 
     Collection<Integer> result = new ArrayList<Integer>(); 
     String query = "SELECT id FROM player WHERE registered_today = true"; 
     //Executing the query with the dataSource 

     return result; 
} 

II。按部件執行此查詢。我的意思是將查詢拆分成4個不相交的部分,並將每個部分執行到一個單獨的線程中(以提高性能)。

public class ConcurrentPlayerDaoImpl implements PlayerDao{ 
    private static final NUMBER_OF_THREADS = 4; 
    private DataSource dataSource; //javax.sql.DataSource 
    //Other methods 
    public Collection<Integer> getPlayerRegisteredIds(){ 
     final Set<Integer> set = Collections.synchronizedSet(new HashSet<Integer>()); 
     //It's going to consist of 4 queries 
     List<String> queriesToConcurrentExecution = new ArrayList<String>();  
     //Obtaining the queries 
     ExecutorService executor = Executors.newFixedThreadPool(NUMBER_OF_THREADS); 
     for(final String sql : queriesToConcurrentExecution){ 
      executor.execute(new Runnable() { 
       @SuppressWarnings("unchecked") 
       @Override 
       public void run() { 
        List<Integer> l = new JdbcTemplate(dataSource).queryForList(sql, Integer.class); 
        set.addAll(l); 
       } 
      }); 
     } 
     executor.shutdown(); 

     return set; 
} 

事情是//Other methods的實施在這兩種情況下是相同的。所以我傾向於將getPlayerRegisteredIds()包裝到某個接口中,然後通過構造函數爲同一個Dao類提供兩種不同的實現。那是對的嗎?

official DAO-pattern's description說,DAO就像一個bussines對象和DataSource之間的適配器,但對我來說,它使用的是本身使用數據源對象。

問題:我們要始終堅持使用DataSource對象直接在DAO?這是必要的要求嗎?

+0

我會說你應該堅持**從來沒有**直接在DAO中使用'DataSource'。 DataSource是Connection的來源,當你的代碼執行多個DAO調用時,它們應該是同一事務的一部分,所以它們必須共享相同的連接。 – Andreas

+0

@Andreas你是什麼意思,多個DAO電話?在同一事務中調用不同DAO的方法? –

+0

DAO實現您的數據訪問邏輯。你的*業務邏輯*調用你的DAO。如果您的業務邏輯需要創建訂單並從存儲中刪除項目(減少庫存盤點),那就是兩個DAO調用,並且它們必須一起發生,因此它們必須在同一個事務中,因此它們必須共享相同的連接。 – Andreas

回答

2

我什麼也看不到根本性的錯誤在你打算用什麼:由DAO使用的接口和包含的具體方法是戰略和DAO將委託給一個或另一個戰略的實施。

DAO仍然具有包含daa訪問方法的角色,並且可以按照自己的方式實現它們,即使這包括委託給其他組件也是如此。

+0

明白了,謝謝。 –

相關問題