MVC案例
1.DAO设计
1.1 DAO
该文件中主要封装了数据的CURD方式,通过让其余的实现类来继承,完成数据库的操作。
底层使用DButils的方式,数据源使用c3p0数据源。
package com.paul.dao;
import com.paul.db.JDBCUtils;
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 java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
/**
* @author Puhao
* @date 2020/2/3
* @brief
*/
public class DAO<T> {
private QueryRunner queryRunner = new QueryRunner();
private Class<T> clazz;
/**
* 需要注意的是,这里都是this(子类构造时)调用的,而this即为子类,所以在这里需要获取其父类的操作
*/
public DAO() {
/*this 调用(CustomerDao extend DAO<Customer>调用,因此要获取其带泛型的父类即DAO<T>)*/
Type superClass = getClass().getGenericSuperclass();
if (superClass instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) superClass;
Type[] typeArguments = parameterizedType.getActualTypeArguments();
if (typeArguments != null && typeArguments.length > 0) {
if (typeArguments[0] instanceof Class) {
clazz = (Class<T>) typeArguments[0];
}
}
}
}
/**
UPDATE DELETE SAVE一些不需结果的操作等
*/
public void update(String sql, Object... agrs) {
Connection connection = JDBCUtils.getConnection();
try {
queryRunner.update(connection, sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.releaseConnection(connection);
}
}
/**
获取POJO对象----->new BeanHandler<>(clazz)
*/
public T get