前兩天一直在搞AngularJs,各種看代碼,昨天晚上要逼近崩潰的時候,決定看點兒別的調解下心情,就換到了MyBatis。
## 一,基本配置
1,引入myBatis的jar包(github地址:[https://github.com/mybatis/mybatis-3/releases](https://github.com/mybatis/mybatis-3/releases)),我使用的是3.3.1這個版本。

2,核心配置文件
示例配置文件我們可以在源碼包里面找到:mybatis\mybatis-3-mybatis-3.3.1\src\test\java\org\apache\ibatis\submitted\complex_property\Configuration.xml
修改我們的連接字符串:

感覺還是跟hibernate蠻像的,別捉急,等用起來,會發現更像。
## 二,編寫基本查詢代碼測試
~~~
/**
* 用來訪問數據庫的類
* @author LiuHuiChao
*
*/
public class DBAccess {
public SqlSession getSqlSession() throws IOException{
//通過配置文件獲取數據庫連接信息
Reader reader=Resources.getResourceAsReader("com/lhc/conofig/Configuration.xml");
//通過配置信息構建sqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
//通過sqlSessionFactory打開一個數據庫會話
SqlSession sqlSession=sqlSessionFactory.openSession();
return sqlSession;
}
}
~~~
mybatis主要是通過一個sqlSession類來進行操作的,以上代碼為創建sqlSession的過程。
編寫一個測試的Entity類:

通過XML文件配置此類與表的對應關系及sql操作語句:
~~~
<mapper namespace="Message">
<resultMap type="com.lhc.bean.Message" id="MessageResult">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="command" jdbcType="VARCHAR" property="command"/>
<result column="description" jdbcType="VARCHAR" property="description"/>
<result column="content" jdbcType="VARCHAR" property="content"/>
</resultMap>
<!-- 通過id調用sql語句,id是要唯一的 -->
<select id="queryMessageList" resultMap="MessageResult">
select id,command,description,content from message where 1=1
</select>
</mapper>
~~~
(還能把sql配置到xml里面,額,,學習了,這個是我大hibernate所沒有的。。。)
最后不要忘記將類的xml引入到核心配置文件中(同hibernate):
~~~
<mappers>
<mapper resource="com/lhc/conofig/sqlXml/Message.xml"/>
</mappers>
~~~
最后, 測試下查詢操作:
~~~
List<Message> messageList=new ArrayList<Message>();
DBAccess dbAccess=new DBAccess();
SqlSession sqlSession=null;
try {
sqlSession=dbAccess.getSqlSession();
//執行sql查詢
messageList=sqlSession.selectList("Message.queryMessageList");
} catch (IOException e) {
e.printStackTrace();
}finally{
sqlSession.close();
}
//通過sqlSession執行sql語句
return messageList;
~~~
未完待續。。。(下面送張我收藏很久的圖。。。)

- 前言
- Spring簡化配置
- Spring中使用AspectJ實現AOP
- Spring中JDK的動態代理和CGLIB代理的區別
- Spring配置問題——元素 "context:component-scan" 的前綴 "context" 未綁定
- Hibernate中編程式事物的簡單使用
- 使用Spring為Hibernate配置聲明式事物
- Struts2+AJAX獲取json數據
- 中間件概述
- EJB(Enterprise Java Bean)概述
- JBoss 6.1安裝配置問題
- EJB對象的部署及客戶端調用簡單示例
- 有狀態的EJB對象和無狀態的EJB對象
- EJB遠程調用和本地調用
- MyBatis——入門select