DBUtils工具类:
DBUtils 可以帮助开发者完成数据的封装(结果集到 java 对象的映射)
ResultSetHandler 接口是用来处理结果集的,可以将查询到的结果转换成 java 对象,主要的 4 个实现类:
- BeanHandler 将结果集映射成 java bean 对象,student
- BeanListHandler 将结果集映射成 List 集合,其范型为 java bean 对象 List
- MapHandler 将结果集映射成 Map 对象,Map<String,Object>
- MapListHandler 将结果集映射成 MapList 集合,List<Map<String,Object>>
用法:
-
导入 jar 包
commons-dbutils-1.7
-
创建 QueryRunner 对象
QueryRunner queryRunner = new QueryRunner();
-
调用 QueryRunner 的 Query() 方法
此方法支持可变参数,值为 PreparedStatement 的占位符的值
queryRunner.query(connection, sql, new BeanHandler<>(StudentEntry.class),num);
其返回值主要看使用哪种实现类封装数据
- 使用 BeanHandler:
需要将实体类类型传入 BeanHandler 中,适合只返回一行数据,如果是多行数据,则只返回第一行数据
结果集:
StudentEntry{id=1, name=‘王五’, score=89.5, birthday=1970-01-01}
public StudentEntry DBUtilsFindByIdToBeanHandler(int num){ QueryRunner queryRunner = new QueryRunner(); String sql = "select * from student where id=?"; List<StudentEntry> list = null; try { connection = comboPooledDataSource.getConnection(); studentEntry = queryRunner.query(connection, sql, new BeanHandler<>(StudentEntry.class),num); } catch (SQLException e) { e.printStackTrace(); } return studentEntry; }
-
使用 BeanListHandler:
同样需要将实体类类型传进去,返回类型是一个 List 集合
结果集:
[StudentEntry{id=1, name=‘王五’, score=89.5, birthday=1970-01-01},
StudentEntry{id=2, name=‘456王五’, score=89.5, birthday=1970-01-01},
StudentEntry{id=3, name=‘456’, score=88.0, birthday=1970-01-01}]
public List<StudentEntry> DBUtilsFindByIdToBeanListHandler(){ List list = null; try { QueryRunner queryRunner = new QueryRunner(); connection = comboPooledDataSource.getConnection(); String sql = "select * from student"; list = queryRunner.query(connection, sql, new BeanListHandler<>(StudentEntry.class)); } catch (SQLException throwables) { throwables.printStackTrace(); } return list; }
-
使用 MapHandler:
适合一行数据,如果是多行,只返回第一行数据
结果集:
{id=2, name=456王五, score=89.5, birthday=1970-01-01}
public Map DBUtilsFindByIdToMapHandler(int num){ Map map = null; try { QueryRunner queryRunner = new QueryRunner(); connection = comboPooledDataSource.getConnection(); String sql = "select * from student where id=?"; map = queryRunner.query(connection, sql, new MapHandler(), num); } catch (SQLException throwables) { throwables.printStackTrace(); } return map; }
-
使用 MapListHandler:
结果集:
[{id=1, name=王五, score=89.5, birthday=1970-01-01},
{id=2, name=456王五, score=89.5, birthday=1970-01-01}]
public List DBUtilsFindByIdToMapListHandler(){ List list = null; try { QueryRunner queryRunner = new QueryRunner(); connection = comboPooledDataSource.getConnection(); String sql = "select * from student"; list = queryRunner.query(connection, sql, new MapListHandler()); } catch (SQLException throwables) { throwables.printStackTrace(); } return list; }