"Architecture Adventure" data access layer code optimization

        Writing code should be a spiral process from complex to simple, and then from simple to complex.

 

        If you don't have money, you should read more e-books. Recently, I read "Architecture Adventure" and wrote something to mark it~

        When I was looking at the code optimization part of the service layer, I remembered the code I wrote during the undergraduate training. A long, long time ago, in a simple and simple training base...

        The code to access the database looks like this:

1. The first is the configuration file:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mytest
jdbc.username=mzuser
jdbc.password=123456

 2. Then load and initialize (mainly logic) in the Dao class:

static{
     conf = loadProperties("config.properties");
     driver = getDriver(conf);
     url = getURL(conf);
     userName = getUserName(conf);
     password = getPassword(conf);

     Class.forName(driver);    //省略try
}

 3. Everything is ready, just owe Dongfeng, access data (for example):

public List<Customer> getCustomerList(){
     try{
     customers = new ArrayList<Customer>();
     sql = "";
     conn = DriverManager.getConnection(url,username,password);
     preparedStatement = conn.prepareStatement(sql);
     resultSet = preparedStatement.executeQuery();
     while(resultSet.next()){
         customer = new Customer();
         set...
         customers.add(customer);
     }
     return customers;
     }catch(SQLExeption e){

     }finally{
         try{
              conn.close()
         }catch(...){
         }
     }
}

 The next step should be to be very happy to keep writing similar code...

        However, when the business continues to grow and more and more codes are used to access the database, you will find that there are a lot of repetitive codes, such as the above initialization and connection acquisition, which is equivalent to setting up a stage to perform, and every time you need to set up a sample In this case, why not set up the stage first, no matter which troupe he is.

       then...

        1. There can be a tool class such as DataBaseHelper to be responsible for loading parameters uniformly, and then encapsulate the code for acquiring and closing connections into methods;

        2. In order to avoid the insecurity of multi-threading, ThreadLocal can be used to isolate connections;

        3. You can use the database connection pool to manage database connections uniformly, such as using BasicDataSource

 

private static final BasicDataSource DATA_SOURCE;

private static final ThreadLocal<Connection> CONNECTION_HOLDER = new ThreadLocal<Connection>();

static {
    Properties conf = PropsUtil.loadProps("config.properties");
    String driver = conf.getProperty("jdbc.driver");
    String url = conf.getProperty("jdbc.url");
    String userName = conf.getProperty("jdbc.username");
    String password = conf.getProperty("jdbc.password");

    DATA_SOURCE = new BasicDataSource();
    DATA_SOURCE.setDriverClassName(driver);
    DATA_SOURCE.setUrl(url);
    DATA_SOURCE.setUsername(userName);
    DATA_SOURCE.setPassword(password);

}

/**
* get connection
*/
public static Connection getConnection(){
    Connection connection = CONNECTION_HOLDER.get();
    if(connection == null){
        try {
            connection = DATA_SOURCE.getConnection();
            CONNECTION_HOLDER.set(connection);
        }catch (SQLException e){
            LOGGER.error("execute sql error", e);
        }
    }

    return connection;
}

        It is said that the QueryRunner object provided by DbUtils can query entity-oriented, like this:

/**
* select list
*/
public static <T> List<T> queryEntityList(Class<T> entityClass, String sql, Object... params){
    List<T> entityList = new ArrayList<T>();
    Connection connection = null;
    try {
        connection = getConnection();
        entityList = QUERY_RUNNER.query(connection, sql, new BeanListHandler<T>(entityClass), params);
    }catch (SQLException e){
        LOGGER.error("query error", e);
    }
    return entityList;
}

        Accessing the database is now as simple as:

public List<Customer> getCustomer(){
    String sql = "select * from customer";
    return DatabaseHelper.queryEntityList(Customer.class, sql);
}

         It looks pretty good, at least the Dao layers will not be as thick as wearing a big padded jacket~

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326771731&siteId=291194637