dimanche 30 août 2015

Can DAO use an object that itself incapsulates a dataSource object?

I have a DAO, (call it PlayerDao) having the following method:

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

Now I need to provide two implementation for that method:

I. Executing a select query on a dataSource directly like the following:

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. Execute this query by parts. I mean split the query into 4 disjoint parts and execute each part into a separate thread (For improving performance).

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

The thing is that implementation of //Other methods is the same in both cases. So I tend to wrap the getPlayerRegisteredIds() into some interface and then provide two different implementation of it for the same Dao class thorugh its constructor. Is that correct?

In the official DAO-pattern's description said that the DAO acts like an adapter between a bussines object and DataSource, but in my case it uses an object that itself uses dataSource.

QUESTION: Should we always adhere to using the dataSource object directly in DAO? Is that the necessary requirement?

Aucun commentaire:

Enregistrer un commentaire