前邊闡述了如何在java項(xiàng)目中使用mybatis,我們使用的是映射文件的方式,在獲得具體的數(shù)據(jù)操作方法時(shí)需要傳入映射文件中namespace+“.”方法名稱,這種方式有時(shí)候會(huì)感覺很不爽,很麻煩。我們?cè)陂_發(fā)中不是常說要面向接口變成嗎,mybatis也支持接口,下面在前面的例子的基礎(chǔ)上做相應(yīng)修改。
前面的例子的環(huán)境及映射文件均保持不變,如下是我的映射文件,
1
2
3
4
5
6
7
8
9
10
11
12
|
<mapper namespace= "com.cn.inter.IMessageOperation" > <select id= "selectUserByID" parameterType= "int" resultType= "com.cn.imooc.entity.Message" > select * from `message` where id = #{id} </select> <select id= "selectMessages" resultType= "Message" > select id, command, description, comment from message; </select> </mapper> |
我們可以看到里邊有namespace為com.cn.inter.ImessageOperation,現(xiàn)在我們創(chuàng)建這樣一個(gè)包,com.cn.inter,在此包中創(chuàng)建接口IMessageOperation,接口中有一個(gè)方法,方法的簽名為:public Message selectUserByID(Integer id);
我們創(chuàng)建的接口和映射文件做了一致對(duì)應(yīng),包括了方法名、返回值、參數(shù)列表。下面看測(cè)試方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
package com.cn.test; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.cn.imooc.entity.Message; import com.cn.inter.IMessageOperation; public class MyTest2 { public static void main(String[] args) { // TODO Auto-generated method stub Reader reader; SqlSession sqlSession= null ; try { //從類路徑下(src)讀取mybatis配置文件 reader=Resources.getResourceAsReader( "Configuration.xml" ); SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(reader); sqlSession=sqlSessionFactory.openSession(); //獲得IMessageOperation接口 IMessageOperation imo=sqlSession.getMapper(IMessageOperation. class ); //調(diào)用接口的方法返回查詢結(jié)果 Message message=imo.selectMessageByIdI( new Integer( 3 )); System.out.println(message); } catch (Exception e){ e.printStackTrace(); } finally { //如果sqlSession不為空,則關(guān)閉 if ( null !=sqlSession) sqlSession.close(); } } } |
我們可以看到測(cè)試方法中調(diào)用數(shù)據(jù)操作的方法發(fā)生了變化,我們是先獲得一個(gè)IMessageOperation的接口,然后調(diào)用其selectMessageByID方法,最后得到結(jié)果。可以感覺到比上一篇中的方式更加簡單了,也更符合我們?nèi)粘5木幋a規(guī)范了。
綜合這兩篇內(nèi)容中的方式,使用任何一種都是可以的,只是兩種不同的方式而已,我個(gè)人更傾向于后者。
以上所述是小編給大家介紹的MyBatis如何使用(二)的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,希望對(duì)大家有所幫助!
原文鏈接:http://www.cnblogs.com/teach/archive/2016/07/23/5699816.html