MyBatis如何使用(二)
前邊闡述了如何在java項(xiàng)目中使用mybatis,我們使用的是映射文件的方式,在獲得具體的數(shù)據(jù)操作方法時(shí)需要傳入映射文件中namespace+“.”方法名稱,這種方式有時(shí)候會(huì)感覺很不爽,很麻煩。我們?cè)陂_發(fā)中不是常說要面向接口變成嗎,mybatis也支持接口,下面在前面的例子的基礎(chǔ)上做相應(yīng)修改。
前面的例子的環(huán)境及映射文件均保持不變,如下是我的映射文件,
<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è)試方法
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é)果??梢愿杏X到比上一篇中的方式更加簡(jiǎn)單了,也更符合我們?nèi)粘5木幋a規(guī)范了。
綜合這兩篇內(nèi)容中的方式,使用任何一種都是可以的,只是兩種不同的方式而已,我個(gè)人更傾向于后者。
以上所述是小編給大家介紹的MyBatis如何使用(二)的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,希望對(duì)大家有所幫助!
相關(guān)文章
java控制臺(tái)實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java控制臺(tái)實(shí)現(xiàn)學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02myeclipse安裝Spring Tool Suite(STS)插件的方法步驟
這篇文章主要介紹了myeclipse安裝Spring Tool Suite(STS)插件的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08String類下compareTo()與compare()方法比較
這篇文章主要介紹了String類下compareTo()與compare()方法比較的相關(guān)資料,需要的朋友可以參考下2017-05-05Java實(shí)體類不要使用基本類型的知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家整理的是關(guān)于Java包裝類之實(shí)體類不要使用基本類型的知識(shí)點(diǎn)內(nèi)容,需要的朋友們可以學(xué)習(xí)下。2020-02-02