-
其实就是封装各种功能
-
dao包存放BasicDAO和各种类DAO
-
-
domain存放各种类
-
-
test用来测试
-
utils存放工具类
basicDAO
import com.jdbc.utils.JDBCUtilsByDruid;
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.sql.Connection;
import java.sql.SQLException;
import java.util.List;
// 其他DAO的父类
public class BasicDAO<T> {
private QueryRunner qr = new QueryRunner();
//开发通用的DML方法,针对任意的表
public int update(String sql, Object... parameters){
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
int update = qr.update(connection, sql, parameters);
return update;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtilsByDruid.closeConnection(null,connection,null);
}
}
/**
*
* @param sql sql语句,可以有占位符?
* @param tClass 传入一个Class类对象,方便反射
* @param parameters 传入占位符?的具体数值,可以是多个
* @return 根据传入的Class类对象,返回对应的ArrayList结果
*/
// 返回多个对象
public List<T> queryMulti(String sql, Class<T> tClass,Object... parameters){
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
List<T> query = qr.query(connection, sql,new BeanListHandler<>(tClass),parameters);
return query;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtilsByDruid.closeConnection(null,connection,null);
}
}
// 返回单行结果
public T querySingle(String sql,Class<T> tClass, Object... parameters){
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
T query = qr.query(connection, sql,new BeanHandler<>(tClass),parameters);
return query;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtilsByDruid.closeConnection(null,connection,null);
}
}
// 返回单值结果,即单行单列
public Object queryScalar(String sql,Object... parameters){
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
Object query = qr.query(connection,sql, new ScalarHandler(), parameters);
return query;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtilsByDruid.closeConnection(null,connection,null);
}
}
}