138.BasicDao
基本说明:
-
DAO:data access object 数据访问对象
-
这样的通用类,称为 BasicDao,是专门和数据库交互的,即完成对数据库(表)的crud操作
-
在BasicDao 基础上,实现一张表对应一个Dao,更好的完成功能,比如 Customer表
代码实现:
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.close(null,null,connection);
}
}
//返回多个对象(即查询的结果是多行的),针对任意表
public List<T> queryMulti(String sql, Class<T> clazz,Object... parameters) {
Connection connection = null;
try{
connection = JDBCUtilsByDruid.getConnection();
return qr.query(connection, sql, new BeanListHandler<T>(clazz), parameters);
} catch (SQLException e) {
throw new RuntimeException(e);//将编译异常转成运行异常
}finally {
JDBCUtilsByDruid.close(null,null,connection);
}
}
//查询单行结果的通用方法
public T querySingle(String sql, Class<T> clazz, Object... parameters) {
Connection connection = null;
try{
connection = JDBCUtilsByDruid.getConnection();
return qr.query(connection, sql, new BeanHandler<T>(clazz), parameters);
} catch (SQLException e) {
throw new RuntimeException(e);//将编译异常转成运行异常
}finally {
JDBCUtilsByDruid.close(null,null,connection);
}
}
//查询单行单列的方法,返回单值的方法
public Object queryScalar(String sql, Object... parameters) {
Connection connection = null;
try{
connection = JDBCUtilsByDruid.getConnection();
return qr.query(connection, sql, new ScalarHandler<>(), parameters);
} catch (SQLException e) {
throw new RuntimeException(e);//将编译异常转成运行异常
}finally {
JDBCUtilsByDruid.close(null,null,connection);
}
}
}
测试ActorDAO 对 actor表的crud操作
public void testActorDAO() {
ActorDAO actorDAO = new ActorDAO();
//1.查询
List<Actor> actors = actorDAO.queryMulti("select * from actor where id >= ?",Actor.class, 1);
System.out.println("===查询结果===");
for(Actor actor : actors) {
System.out.println(actor);
}
//2.查询单行记录
Actor actor = actorDAO.querySingle("select * from actor where id = ?",Actor.class, 1);
System.out.println("===查询单行结果===");
System.out.println(actor);
}
//3.查询单行单列
Object o = actorDAO.queryScalar("select name from actor where id = ?",6);
System.out.println("===查询单行单列值===");
System.out.println(o)
//4. dml操作 insert,update,delete
int update = actorDAO.update("insert into actor values(null,?,?,?,?)","张无忌","男","2000-1-1","111");
System.out.println(update > 0 ? "执行成功" : "执行没有影响表");
}