咱們在mapper.xml寫sql,若是都是一個參數,則直接配置parameterType,那實際業務開發過程當中多個參數如何處理呢?html
從MyBatis API中發現selectOne和selectLit方法重載第一個傳statement,第二個傳Object。那麼咱們則用Map來傳多個參數。java
開發環境、pom.xml、mapper.xml、log4j.properties同上文。sql
<select id="queryUserByAddress" resultType="com.autohome.model.User"> select * from t_userinfo where name=#{name,javaType=String,jdbcType=VARCHAR} and address=#{address} </select>
建立Map傳參,map的key值和mapper sql參數名稱相對應。mybatis
@Test
public void queryUserByNameAddress(){
SqlSession sqlSession=null;
try{
sqlSession=sqlSessionFactory.openSession();
Map<String,Object> map =new HashMap<String,Object>(); map.put("name","kobe"); map.put("address","usa"); User user = sqlSession.selectOne("com.autohome.mapper.User.queryUserByAddress",map); System.out.println("id:"+user.getId()+",name:"+user.getName()+","+user.getAddress()); }catch(Exception e){ e.printStackTrace(); }finally { sqlSession.close(); } }
在看mybatis API時發現了rowbounds參數,能夠用來實現分頁,不過他並非直接在sql中實現,只是在查詢結果集的基礎上實現數據分頁,小數量可用,大數據量則不推薦,也權當是作個demoapp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
@Test
public void queryPagedUsers(){
SqlSession sqlSession= null ;
try {
sqlSession=sqlSessionFactory.openSession();
RowBounds row= new RowBounds( 10 , 10 );
List<User> list = sqlSession.selectList( "com.autohome.mapper.User.queryUsers" , null ,row);
System.out.println( "size:" +list.size());
for (User user:list){
System.out.println( "id:" +user.getId()+ ",name:" +user.getName()+ "," +user.getAddress());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
|
附DEBUG截圖post
起初學習java時老是不知從何學起,總算是在跌跌撞撞中入了門,我本身總結爲學習java沒什麼捷徑可言,惟能作的就是敲demo 看文檔、敲demo 看文檔、敲demo 看文檔。單元測試