六.BasicDao
将各个Dao共同操作就全部集成到BasicDAO,简化代码;
DAO = dara access object -- 数据访问对象
BASICDAO代码
/**
* @className: com.jdbc.dao.BasicDao
* @description: TODO
* @author: XiaoDai
* @create: 2022-10-22 9:37
*/
public class BasicDao<T> {
private QueryRunner qr = new QueryRunner();
//通用DML操作
public int update(String sql, Object... parameters) {
Connection connection = null;
try {
connection = Utils_.getConnection();
int affect = qr.update(connection, sql, parameters);
return affect;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
Utils_.close(null, null, connection);
}
}
//返回多行结果,用list
/**
* @param sql sql语句
* @param tClass 传入类的Class对象,才知道我们要转换成什么对象
* @param parameters 可变形参
* @return
*/
public List<T> queryMany(String sql, Class<T> tClass, Object... parameters) {
Connection connection = null;
try {
connection = Utils_.getConnection();
return qr.query(connection, sql, new BeanListHandler<T>(tClass), parameters);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
Utils_.close(null, null, connection);
}
}
//单行查询
public T querySingle(String sql, Class<T> tClass, Object... parameters) {
Connection connection = null;
try {
connection = Utils_.getConnection();
return qr.query(connection, sql, new BeanHandler<T>(tClass), parameters);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
Utils_.close(null, null, connection);
}
}
//单行某列查询
public Object queryScalar(String sql, Object... parameters) {
Connection connection = null;
try {
connection = Utils_.getConnection();
return qr.query(connection, sql, new ScalarHandler<>(), parameters);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
Utils_.close(null, null, connection);
}
}
}
ActorDao--测试表Dao
public class ActorDao extends BasicDao<Actor>{
//增加一些ActorDao特有的方法
}
对ActorDao的测试
@Test
public void testDao() {
ActorDao actorDao = new ActorDao();
String sql = "select * from actor where id >= ?";
List<Actor> actors = actorDao.queryMany(sql, Actor.class, 1);
for (Actor actor : actors) {
System.out.println(actor);
}
System.out.println("--------------------------------------------");
String sql1 = "select * from actor where id = ?";
Actor actor = actorDao.querySingle(sql1, Actor.class, 2);
System.out.println(actor);
System.out.println("--------------------------------------------");
String sql2 = "select name from actor where id = ?";
Object obj = actorDao.queryScalar(sql2, 2);
System.out.println(obj);
//演示dml
System.out.println("--------------------------------------------");
int update = actorDao.update("insert into actor values(null,?,?,?,?)", "dmx", "女", "2000-01-02", "113");
System.out.println("受影响行数 = " + update);
}