java之mybatis之查询及分页
1.mybatis中查询方式有3种
//查询单个值 @Test public void testFindOne()throws IOException{ SqlSession session = MybatisUtil.getSqlSession(); User user = (User)session.selectOne("cn.sxt.vo.UserMapper.findOne", 1); System.out.println(user); session.close(); } //查询list @Test public void testFindAll() throws IOException{ SqlSession session = MybatisUtil.getSqlSession(); List<User> list = session.selectList("cn.sxt.vo.UserMapper.findAll"); for(User u:list){ System.out.println(u); } session.close(); } //查询map @Test public void testFindMap()throws IOException{ SqlSession session = MybatisUtil.getSqlSession(); //selectMap 传递的参是 map集合的key值。 Map map=session.selectMap("cn.sxt.vo.UserMapper.findMap", "name"); for(Iterator iter=map.keySet().iterator();iter.hasNext();){ Object key=iter.next(); System.out.println(key+"---"+map.get(key)); } session.close(); }
映射文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.sxt.vo.UserMapper"> <!-- 查询单个对象 --> <select id="findOne" resultType="User"> select * from t_user where id=#{id} </select> <!-- 查询list --> <select id="findAll" resultType="User"> select * from t_user </select> <!-- 查询map --> <select id="findMap" resultType="Map"> select * from t_user where id=1 </select> <!-- begin=(currentPage-1)*pageSize size=pageSize --> <select id="page1" resultType="User"> select * from t_user limit #{begin},#{size} </select> <select id="pageRow" resultType="User"> select * from t_user </select> </mapper>
2.分页
mybatis中有3种方式实现分页
映射文件
<select id="page1" resultType="User"> select * from t_user limit #{begin},#{size} </select> <select id="pageRow" resultType="User"> select * from t_user </select>
代码
//通过sql语句进行分页,参数传入的是对象 @Test public void testPage() throws IOException{ SqlSession session = MybatisUtil.getSqlSession(); PageInfo pi = new PageInfo(); pi.setBegin(3); pi.setSize(3); List<User> list = session.selectList("cn.sxt.vo.UserMapper.page1",pi); for(User u:list){ System.out.println(u); } } //通过sql语句进行分页,参数传入的是map @Test public void testPage1() throws IOException{ SqlSession session = MybatisUtil.getSqlSession(); Map map = new HashMap(); map.put("begin", 0); map.put("size", 3); List<User> list = session.selectList("cn.sxt.vo.UserMapper.page1",map); for(User u:list){ System.out.println(u); } } //通过RowBounds来实现分页 @Test public void testPage2() throws IOException{ SqlSession session = MybatisUtil.getSqlSession(); //第一个 参数 相当于index,第二个参数 每页显示记录数 RowBounds bounds = new RowBounds(3, 3); List<User> list = session.selectList("cn.sxt.vo.UserMapper.pageRow",null,bounds); for(User u:list){ System.out.println(u); } }