黑猴子的家:Stock(八) 创建 BasicDao 模板工具类

1、bean 包下右键 –> New -> Class
2、Name -> BasicDao -> Finish
3、BasicDao –> code内容
package com.yg.bean;

import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
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.yg.utils.JDBCUtils;

/**
 * @author 黑猴子的家
 * @博客 https://www.jianshu.com/u/37fd8e2dff4c
 * 
 * DAO层有哪些功能
 *   1、增删改
 *   2、查询单个对象
 *   3、查询单个值
 *   4、查询多个对象
 */
public class BasicDao {
      
      Class clazz;
      QueryRunner qr;

      @SuppressWarnings({ "unchecked", "rawtypes" })
      //构造器Users 
      public BasicDao() {
            qr = new QueryRunner();
            // 获取父类的泛型
            // UsersDao.class
            Class c = this.getClass();
            // BasicDao
            ParameterizedType type = (ParameterizedType) c.getGenericSuperclass();
            // Users
            clazz = (Class) type.getActualTypeArguments()[0];
      }

      /**
       * 增删改
       * @param sql
       * @param objects
       * @return
       * @throws Exception
       */
      public int update(String sql, Object... objects) throws Exception {
            Connection connection = JDBCUtils.getConnection();
            int update = qr.update(connection, sql, objects);
            connection.close();
            return update;
      }

      /**
       * 查询单个对象
       * @param sql
       * @param objects
       * @return
       * @throws Exception
       */
      public T querySingle(String sql, Object... objects) throws Exception {
            Connection connection = JDBCUtils.getConnection();
            //dbutil 开源框架
            T t = qr.query(connection, sql, new BeanHandler(clazz), objects);
            connection.close();
            return t;
      }

      /**
       * 查询多个对象
       * 
       * @param sql
       * @param objects
       * @return
       * @throws Exception
       */
      public List queryList(String sql, Object... objects) throws Exception {
            Connection connection = JDBCUtils.getConnection();
            List list = qr.query(connection, sql, new BeanListHandler(clazz), objects);
            connection.close();
            return list;

      }

      /**
       * 查询一个值  就是一个字段  name  
       * 
       * @param sql
       * @param objects
       * @return
       * @throws Exception
       */
      public Object scalar(String sql, Object... objects) throws Exception {
            Connection connection = JDBCUtils.getConnection();
            Object query = qr.query(connection, sql, new ScalarHandler(), objects);
            connection.close();
            return query;

      }
}

你可能感兴趣的:(黑猴子的家:Stock(八) 创建 BasicDao 模板工具类)