Day4_JDBC-BaseDao Class Optimization

Posted by bellaso on Tue, 08 Oct 2019 12:16:30 +0200

I. analysis.

From last article Day3_JDBC - Encapsulation of Addition, Deletion and Change Checks (BaseDao class) using DBUtils third-party tools As you can see, every method in the BaseDao class needs to pass in a type of entity class (that is, JavaBean type). If we inherit the BaseDao class, we tell the constructor of BaseDao directly the type of my entity class, so that we no longer need to pass in an entity class type in the method.

Two. Example

The catalogue structure of this project is as follows:

BaseDao2.java

package com.atguigu.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.atguigu.utils.JDBCUtils;

public class BaseDao2<T> {
          private QueryRunner runner = new QueryRunner();
          private Class<T> type;//The purpose is to assign T to type, that is, to get the generic type of BaseDao2 and give it to type.
          
          /*
           * BaseDao2 does not create objects directly by getting generic types of classes in a parametric constructor
           * BaseDao2 this in the constructor represents subclass objects
           */
           public BaseDao2() {
        	   //1. Get the class template of the subclass object, UserDao2 extends BaseDao2 < User >
        	   Class<? extends BaseDao2> cla = this.getClass();
        	   //2. Get the generic type of the parent class
        	   //cla.getSuperclass(); Gets the parent type BaseDao2
        	   ParameterizedType pt = (ParameterizedType) cla.getGenericSuperclass();//Get the real parent type BaseDao2 < User >
        	   //3. Get a list of generics, a class can declare multiple generic parameters Map < K, V >
        	   Type[] types = pt.getActualTypeArguments();
        	   //4. The generic type that takes the first place is the generic type of BaseDao2.
        	  type = (Class<T>) types[0];
           }
          
          //Additions and deletions
          public int update(String sql, Object...params) {
        	  Connection conn = JDBCUtils.getConn();
        	  int count = 0;
              try {
				count = runner.update(conn, sql, params);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				JDBCUtils.closeConn(conn);
			}
        	 return count; 
          }
          
          //A method of querying a record encapsulated as an object
          public T getBean( String sql, Object...params){
        	  Connection conn = JDBCUtils.getConn();
        	  T t = null;
        	  try {
        		  //BeanHandler encapsulates the queried record as an object
        		  //The type class must be constructed by a parametric constructor, and the attribute name of the type class must be consistent with the column name of the sql query.
				t = runner.query(conn, sql, new BeanHandler<>(type), params);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("t For:" + t);
			}finally {
				JDBCUtils.closeConn(conn);
			}
        	  return t;
          }
          
          //Query multiple records and encapsulate them as a collection of objects
          public List<T> getBeanList( String sql, Object...params){
        	  Connection conn = JDBCUtils.getConn();
        	  List<T> list = null;
        	  try {
				list = runner.query(conn, sql, new BeanListHandler<>(type), params);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				JDBCUtils.closeConn(conn);
			}
        	  return list;
          }
          
          //The total number of records in the database table is queried. The list of variable parameters is 0 to n parameters.
          //If there are no parameters, there is no need to pass in a list of variable parameters, nor even null.
          public long getCount(String sql, Object...params) {
        	  Connection conn = JDBCUtils.getConn();
        	  //ScalarHandler: The parametric constructor defaults to encapsulate the first row and first column of data queried as object returns
        	  //              If it is an integer type, return the true type Long
        	  //              If the true return type is String and promoted to Object return
        	  long count = 0;
        	  try {
				count = (long) runner.query(conn, sql, new ScalarHandler(), params);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				JDBCUtils.closeConn(conn);
			}
        	  return count;
          }
          
          //Batch add and delete, it needs to know how many times to execute, what is the parameter of each time?
          //So the two-dimensional data parameters in the method, the first dimension represents the number of batch executions.
          //The second dimension represents the list of parameters required for each batch.
          public void batchUpdate(String sql, Object[][] params) {
        	  Connection conn = JDBCUtils.getConn();
        	  try {
				runner.batch(conn, sql, params);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				JDBCUtils.closeConn(conn);
			}
          }
          
}

Topics: SQL Java Apache Attribute