对于Apache dbutils有两个主要的类/接口,分别是QueryRunner和ResultSetHandler,下面是解释:
上代码
package net.xdclass.forum.dao;
import net.xdclass.forum.domain.Category;
import net.xdclass.forum.util.DataSourceUtil;
import org.apache.commons.dbutils.*;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
/**
* @author jiangjw
* @version 1.0.1
* @date 2022/3/10 15:57
* @use:
*/
public class CategoryDao {
private QueryRunner queryRunner=new QueryRunner(DataSourceUtil.getDataSource());
//开启驼峰映射
private BeanProcessor beanProcessor=new GenerousBeanProcessor();
private RowProcessor processor=new BasicRowProcessor(beanProcessor);
/**
* 根据id找分类
* @param id
* @return
*/
private Category findById(int id){
String sql="select * from category where id=?";
Category category=null;
try {
category=queryRunner.query(sql,new BeanHandler<>(Category.class,processor),id);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return category;
}
/**
* 返回分类列表
*/
private List<Category> list(){
String sql="select * from category where id=?";
List<Category> list=null;
try {
list=queryRunner.query(sql,new BeanListHandler<>(Category.class,processor));
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return list;
}
}
首先解释下面这行
category=queryRunner.query(sql,new BeanHandler<>(Category.class,processor),id);
这里query的几个参数逐一解释:sql是数据库语法,new BeanHandler<>()是ResultSetHandler下的一个方法,上文有,他的两个参数:Category.class是映射到要返回结果的类,processor是驼峰映射,这里要设置驼峰,因为query将数据库的结果逐一返回到user对象中,但是此时user是驼峰命名的;下一个参数id是sql命令里面的参数;
接下来讲解update:
public int save(User user) throws Exception {
String sql="insert into user (phone,pwd,sex,img,create_time,role,username,wechat) values(?,?,?,?,?,?,?,?)";
Object[] params={
user.getPhone(),
user.getPwd(),
user.getSex(),
user.getImg(),
user.getCreateTime(),
user.getRole(),
user.getUsername(),
user.getWechat()
};
// String sql = "delete from user where id= ?";
// Object [] params = {15};
int i=0;
try {
i= queryRunner.update(sql,params);
}catch (Exception e){
e.printStackTrace();
throw new Exception();
}
return i;
}
注意这里update返回的不是object,而是int数据,还有update是不需要设置驼峰映射的(大家可以自己思考一下),原因是:update并不向user对象逐一返回值,他只是修改数据库的值,而向数据库传值的时候,并不对变量名有要求,只要求位置相对应就可以。