国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

MyBatis如何使用(二)

2019-11-26 14:02:09
字體:
來源:轉載
供稿:網友

前邊闡述了如何在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如何使用(二)的相關資料,非常不錯,具有參考借鑒價值,希望對大家有所幫助!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 桦甸市| 五莲县| 岚皋县| 肥城市| 嘉禾县| 鹤壁市| 嘉祥县| 都兰县| 长泰县| 津南区| 堆龙德庆县| 当阳市| 乡宁县| 乐昌市| 青州市| 新丰县| 上杭县| 会理县| 三门县| 修武县| 鲜城| 星座| 垫江县| 丽水市| 彝良县| 郎溪县| 阳泉市| 阳信县| 临夏县| 同江市| 梓潼县| 南华县| 陵水| 辛集市| 白河县| 敦化市| 礼泉县| 南和县| 哈尔滨市| 威信县| 栖霞市|