DAO and dependency injection, advice?

后端 未结 4 1001
谎友^
谎友^ 2021-01-13 12:08

This is the first time im using the DAO pattern. From what I\'ve read so far, implementing this pattern will help me seperate my calling code (controller) from any persisten

4条回答
  •  长情又很酷
    2021-01-13 12:32

    A "pluggable" DAO layer is usually/always based on an interface DAO. For example, lets consider a quite generic simple one:

    public interface GenericDAO  {  
        List getAll(Class typeClass);   
        T findByKey(Class typeClass, K id);  
        void update(T object);  
        void remove(T object);  
        void insert(T object);  
    }
    

    (This is what you have in Morphia's generic DAO)

    Then you can develop different several generic DAO implementations, where you can find different fields (reflected in constructor parameters, setters and getters, etc). Let's assume a JDBC-based one:

    public class GenericDAOJDBCImpl implements GenericDAO {
        private String db_url;
    
        private Connection;
        private PreparedStatement insert;
        // etc.
    }
    

    Once the generic DAO is implemented (for a concrete datastore), getting a concrete DAO would be a no brainer:

    public interface PersonDAO extends GenericDAO {
    
    }
    

    and

    public class PersonDAOJDBCImpl extends GenericDAOJDBCImpl implements PersonDAO {
    
    }
    

    (BTW, what you have in Morphia's BasicDAO is an implementation of the generic DAO for MongoDB).

    The second thing in the pluggable architecture is the selection of the concrete DAO implementation. I would advise you to read chapter 2 from Apress: Pro Spring 2.5 ("Putting Spring into "Hello World") to progressively learn about factories and dependency injection.

提交回复
热议问题