项目场景:
今天在做一个JavaWeb项目时,在测试Dao类时,发现用DButils查到的数据为空,控制台没报错。
问题描述:
BaseDao关键代码:private static QueryRunner queryRunner=new QueryRunner();
public <T> T queryForBean(Class<T> type,String sql,Object...args){
try {
Connection connection= JdbcUtils.getConnection();
return queryRunner.query(connection,sql, new BeanHandler<T>(type),args);
} catch (Exception throwables) {
throwables.printStackTrace();
}
return null;
}
StuDao实现类关键代码:
public class StuDaoImpl extends BaseDao implements StuDao {
@Override
public Student findByNo(String stuNo) {
Student student = queryForBean(Student.class, "select id,stuNo,stuName,stuSex,stuAge,stuAdd from t_stu where stuNo=?", stuNo);
return student;
}
}
测试类:
@Test
public void findByNo() {
System.out.println(stuDao.findByNo("303001"));
}
结果查询后返回的Bean对象为空(或者该对象的属性为空值)
原因分析:
QueryRunner通过BeanHandler类来实现将数据表中的数据封装成实体对象,要求数据表中的列名和实体类中的属性名一致。