There are ways to search in 1.mybatis 3 Zhong
//查询单个值 @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(); }
Mapping file
<?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. Paging
mybatis There are three ways to implement paging
Mapping file
<select id="page1" resultType="User"> select * from t_user limit #{begin},#{size} </select> <select id="pageRow" resultType="User"> select * from t_user </select>
Code
// paged by sql statement, the object is passed as an argument @Test public void TestPage () throws IOException { the SqlSession the session = MybatisUtil.getSqlSession (); PageInfo PI = new new PageInfo (); pi.setBegin ( . 3 ); PI. the setSize ( . 3 ); List . <the User> List = the session selectList is ( "cn.sxt.vo.UserMapper.page1" , PI ); for (the User U: List) { System.out.println (U); } } / / paging through sql statement, parameters are passed in 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 { the SqlSession the session = MybatisUtil.getSqlSession (); // The first parameter corresponds to the index, the second parameter number of records per RowBounds bounds = new new RowBounds (. 3,. 3 ); List <the User> = session.selectList List ( "cn.sxt.vo.UserMapper. pageRow ", null , bounds ); for (the User U: List) { System.out.println (U); } }