前邊闡述了如何在java項目中使用mybatis,我們使用的是映射文件的方式,在獲得具體的數據操作方法時需要傳入映射文件中namespace+“.”方法名稱,這種方式有時候會感覺很不爽,很麻煩。我們在開發中不是常說要面向接口變成嗎,mybatis也支持接口,下面在前面的例子的基礎上做相應修改。
前面的例子的環境及映射文件均保持不變,如下是我的映射文件,
<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,commentfrom message;</select></mapper>我們可以看到里邊有namespace為com.cn.inter.ImessageOperation,現在我們創建這樣一個包,com.cn.inter,在此包中創建接口IMessageOperation,接口中有一個方法,方法的簽名為:public Message selectUserByID(Integer id);
我們創建的接口和映射文件做了一致對應,包括了方法名、返回值、參數列表。下面看測試方法
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 stubReader 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);//調用接口的方法返回查詢結果Message message=imo.selectMessageByIdI(new Integer(3));System.out.println(message);}catch(Exception e){e.printStackTrace();}finally{//如果sqlSession不為空,則關閉if(null!=sqlSession)sqlSession.close();}}}我們可以看到測試方法中調用數據操作的方法發生了變化,我們是先獲得一個IMessageOperation的接口,然后調用其selectMessageByID方法,最后得到結果。可以感覺到比上一篇中的方式更加簡單了,也更符合我們日常的編碼規范了。
綜合這兩篇內容中的方式,使用任何一種都是可以的,只是兩種不同的方式而已,我個人更傾向于后者。
以上所述是小編給大家介紹的MyBatis如何使用(二)的相關資料,非常不錯,具有參考借鑒價值,希望對大家有所幫助!
新聞熱點
疑難解答