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(); Listlist = 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(); }
映射文件
2.分页
mybatis中有3种方式实现分页
映射文件
代码
//通过sql语句进行分页,参数传入的是对象 @Test public void testPage() throws IOException{ SqlSession session = MybatisUtil.getSqlSession(); PageInfo pi = new PageInfo(); pi.setBegin(3); pi.setSize(3); Listlist = 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 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 list = session.selectList("cn.sxt.vo.UserMapper.pageRow",null,bounds); for(User u:list){ System.out.println(u); } }