ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
查询常用方法如下: <br/> **1. `Map<String, Object> queryForMap(String sql, @Nullable Object... args)`** ```java String sql = "select id, name, age, gender from student where id=?"; //返回的Map类为LinkedCaseInsensitiveMap,该类的key不区分大小写 Map<String, Object> dataMap = jdbcTemplate.queryForMap(sql, new Object[]{51}); ``` **2. `<T> List<T> query(String sql, RowMapper<T> rowMapper)`** ```java String sql = "select id, name, age, gender from student"; List<Student> dataList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class)); ``` **3. `<T> List<T> query(String sql, RowMapper<T> rowMapper, @Nullable Object... args)`** ```java String sql = "select id, name, age, gender from student where id = ?"; List<Student> dataList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class), new Object[]{51}); ``` **4. `<T> List<T> query(String sql, @Nullable PreparedStatementSetter pss, RowMapper<T> rowMapper)`** ```java String sql = "select id, name, age, gender from student where id = ?"; List<Student> dataList = jdbcTemplate.query(sql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setInt(1, 51); } }, new BeanPropertyRowMapper<>(Student.class)); ``` **5. `List<Map<String, Object>> queryForList(String sql)`** ```java String sql = "select id, name, age, gender from student"; //返回的Map类为LinkedCaseInsensitiveMap,该类的key不区分大小写 List<Map<String, Object>> dataList = jdbcTemplate.queryForList(sql); ``` **6. `<T> List<T> queryForList(String sql, Class<T> elementType)`** ```java //只能查询一列 String sql = "select name from student"; List<String> dataList = jdbcTemplate.queryForList(sql, String.class); ``` **7. `List<Map<String, Object>> queryForList(String sql, @Nullable Object... args)`** ```java String sql = "select id, name, age, gender from student where id=?"; //返回的Map类为LinkedCaseInsensitiveMap,该类的key不区分大小写 List<Map<String, Object>> dataList = jdbcTemplate.queryForList(sql, new Object[]{51}); ``` **8. ` <T> List<T> queryForList(String sql, Class<T> elementType, @Nullable Object... args)`** ```java //只能查询一列 String sql = "select name from student where id=?"; List<String> dataList = jdbcTemplate.queryForList(sql, String.class, new Object[]{51}); ``` **9. 分页查询** `<T> List<T> query(String sql, RowMapper<T> rowMapper, @Nullable Object... args)` ```java //当前页 int page = 1; //页面大小 int size = 10; String sql = "select id, name, age, gender from student where gender=? limit ?,?"; List<Student> dataList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class), new Object[]{"男", (page - 1) * size, size}); ``` **10. Oracle的分页查询语句** ```sql SELECT * FROM (SELECT A.*,ROWNUM AS RN FROM (SELECT * FROM ${tableName} WHERE 1=1 -- 条件 ORDER BY CREATETIME DESC,ID -- 排序 ) A WHERE A.ROWNUM <= #{pageNum}*#{pageSize} ) B WHERE B.RN > #{pageNum-1}*#{pageSize} /* 由于oracle排序算法问题,如果排序遇到相同的条件,比如时间, 会使分页后一页包含前一页的内容,所以这个时候添加一个唯一的字段,比如ID。 */ ```