1、什么是iBATIS
1.1作者
Clinton Begin,很牛X的名字
1.2背景故事
Clinton Begin于2001年啟動iBATIS項目,最先的焦點是發展密碼軟件解決方案。第一個iBATIS產品是Secrets,是一個象PGP的個人數據加密器和簽名工具。Secrets完全用Java編寫并在一個開源許可下發布。
在發布Secrets Java版后不久,iBATIS項目陷入困境轉而關注Web和其它internet相關的技術,在接下來的一年中,兩個有趣的軟件開發完成,包括Axle web 框架,一個JSP可選工具。Lookout郵件客戶端差不多完成90%在 being set on the back burner之前,同時更多有趣的挑戰接踵而來…
1.3加入Pet Store“基準”
在2002年早些時候,Microsoft發布一個紙面文檔聲稱.NET有10倍于J2EE的速度和4倍多的生產效率。事實是這只是簡單的而不是典型的。iBATIS項目在2002年7月1日快速回應,JPetStore 1.0發布了。基于相同的Pet Store需求,JPetStore證明了Java不僅比.NET更有生產效率,同時比Microsoft的實現擁有更好的架構。
JPetStore利用有趣的持久層迅速地引起了開源社區的關注。在JPetStore發布不久,對SQL Maps和DAO框架的問題和要求使大家知道的iBATIS Database Layer產生了。iBATIS Database Layer包含兩個被打包在一起的框架:SQL Maps和DAO。
如今iBATIS項目重點關注持久層框架并以SQL Maps 和 Data Access Objects (DAO)著稱。JPetStore繼續作為這些框架典型應用的官方示例程序。
1. 4“iBATIS”是什么意思
現在,單詞“ibatis”和SQL Maps 與 DAO 框架同義――就象“xerox”『施樂復印機(商標名稱),譯者著』和“photocopy” 『影印,譯者著』同義。
回想起iBATIS來源于密碼系統軟件。iBATIS實際上用兩個單詞的組合來命名:“internet” 和 “abatis”。
Reference.com 如此定義 abatis:
ab-a-tis
n. pl. ab-a-tis (-tz) or ab-a-tis-es (-t-sz)
將伐倒的樹木樹枝相互交叉,放置,有時削尖,面對敵人一種防御障礙物。
將“Internet”中象征性的“i”和abatis中的“batis”組合所以暗示了抵御Internet的意思。-in the case of iBATIS它是Secrets提供的關于密碼防御的東西。
所以iBATIS正確的寫法應該是:iBATIS
1.5 iBATIS怎么念?
因為我們發明了這個單詞,我們以自己喜歡的讀音念它
我們這樣讀:eye-BAT-iss
但是按照傳統,它可能應該被讀作:eye-BATE-iss,但就象我們說的,我們創造了它。
1.6許可(License)
iBATIS的源碼和文檔在Apache License 2.0許可下發布。
1.7版本情況
iBATIS有for Java,for .NET,for Ruby三個語言的版本,以下主要討論for Java版,也是最重要的版本。
關于版本,看下面一段英文:
iBATIS 3.0 Whiteboard
January 11th, 2007 marks the 3rd Anniversary(周年紀念) of the iBATIS 2.0. It has served the community well for three years, but times change. The year 2006 was full of innovation(改革、創新) and shifts in technology and mindset. The impact(沖擊,碰撞) of frameworks like Ruby on Rails cannot be ignored. The industry has noticed and finally invested in lightweight frameworks, agile principles and simple solutions first.
最新版本:iBATIS2.3.0 build667,非常穩定。
1.8 典型用戶
MySpace.com - A place for friends
…
2、當前Java平臺下的一些DAO框架
2.1Hibernate
應該是最好的ORM框架,ORM:Object Relation Mapping,即對象關系映射。
了解不是很多,不多作評價。不過應該是很好的框架,EJB3里的JPA所說差不多就是簡化版的Hibernate,側重于對象模型設計,系統設計中數據庫設計讓位于對象模型設計。
2.2 Apache JDO
Apache組織的一個比較早的開源框架,影響力不大。
2.3 Spring DAO(Template)
Spring DAO對JDBC進行了封裝
用得最多的還是各種Template:
JdbcTemplate
HibernateTemplate
SqlMapTemplate
JdoTemplate
JpaTemplate
2.4 JDBC
對數據庫操作最原始的辦法,也是根本,無所不能的。
2.5 iBATIS
又稱為SQL Map或 Data Map(2.0以后)
SQL Mapping framework 更準確地說是 SQL Mapping tool,是一個SQL語句映射的框架(工具)
2.5.1介紹(Introduction)
The iBATIS Data Mapper framework will help you to significantly(意味深長地,值得注目地) reduce the amount of Java code that you normally need to access a relational database. iBATIS simply maps(此處應譯作映射) JavaBeans to SQL statements using a very simple XML descriptor. Simplicity(簡單) is the key advantage(優勢,有利條件) of iBATIS over other frameworks and object relational mapping tools. To use the iBATIS Data Mapper you need only be familiar with JavaBeans, XML and SQL. There is very little else to learn. There is no complex scheme required to join tables or execute complex queries. Using Data Mapper you have the full power of real SQL at your fingertips.
2.5.2 概念(Concept)
The iBATIS Data Mapper API allows programmers to easily map JavaBeans objects to PreparedStatement parameters and ResultSets. The philosophy behind Data Mapper is simple: provide a simple framework to provide 80% of JDBC functionality using only 20% of the code.
3、學習iBATIS
3.1 一個簡單的iBATIS原型
SELECT COUNT(*) FORM USER
討論:
一、用JDBC直接在頁面中如何寫程序
二、多個JSP文件同時出現此功能時
三、出現不同的版本,SELECT COUNT(*) FORM USER WHERE USER_TYPE=1 AND IS_DEL=0…
四、討論各個版本的輸入輸出參數
3.2 iBATIS 藏寶圖
討論:iBATIS各種輸入輸出參數
3.3 iBATIS API(Spring SqlMapClientTemplate API)
第一個參數statementName都是必須的,其它參數都是可選的
增、刪、改
public Object insert(String statementName, Object parameterObject)
public int update(String statementName, Object parameterObject)
public int delete(String statementName, Object parameterObject)
查詢
public Object queryForObject(String statementName, Object parameterObject)
public List queryForList(String statementName, Object parameterObject)
void queryWithRowHandler (String statementName, Object parameterObject, RowHandler rowHandler) 不常用
public PaginatedList queryForPaginatedList(String statementName, Object parameterObject, int pageSize) 性能問題,已經被廢棄(deprecated)
public Map queryForMap (String statementName, Object parameterObject, String keyProperty, String valueProperty)
沒有了…
4.使用iBATIS的好處
4.1簡單,學習曲線低
4.2使用公司投資回報率提高,一般是5到8倍
4.3喝著Java(咖啡)寫Java代碼,節省大量編碼維護時間
4.4提高員工土氣
4.5性能好,靈活性強
4.6集中管理后,DAO的實現簡單,使用開發人員更專心于業務邏輯的處理。修改時不用修改Java代碼。
4.7使用preparedStatement,性能,安全性提高,代碼簡潔。
4.8配置log4j在調試時輸出SQL語句和返回記錄集,漫天飛舞的System.out.print不見了。
4.9不用擔心,連接、記錄集的關閉
4.10緩存,討論:很小變動的基礎數據。
4.11寫程序時很自然地優化SQL,減少數據庫的連接次數和操作次數
討論:
一級分類1
二級分類1.1 二級分類1.2
一級分類2
二級分類2.1 二級分類2.2
一級分類3
二級分類3.1 二級分類3.2
討論遺漏的好處。
討論缺點
5.iBATIS的配置文件
有兩種:
5.1 sqlMapConfig文件
只有一個,集中管理配置文件的“中央文件”
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<settings cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
useStatementNamespaces="false"
statementCachingEnabled="true"
classInfoCacheEnabled="true" />
<sqlMap resource="com/ahtec/ssi/dao/ibatis/maps/SysModule.xml" />
<sqlMap resource="com/ahtec/ssi/dao/ibatis/maps/EudProject.xml" />
</sqlMapConfig>
5.1 各個SQL Map 文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="dv_bbslink">
<typeAlias alias="link" type="com.ahtec.ssi.domain.Link" />
<cacheModel id="oneDayCache" type="OSCACHE">
<flushInterval hours="24" />
<flushOnExecute statement="insertLink" />
<flushOnExecute statement="updateLinkByPrimaryKey" />
<flushOnExecute statement="updateLinkByPrimaryKeySelective" />
<flushOnExecute statement="deleteLinkByPrimaryKey" />
<flushOnExecute statement="deleteLink" />
</cacheModel>
<resultMap class="com.ahtec.ssi.domain.Link" id="LinkResult">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="boardname" jdbcType="VARCHAR" property="boardname" />
<result column="readme" jdbcType="VARCHAR" property="readme" />
<result column="url" jdbcType="VARCHAR" property="url" />
<result column="logo" jdbcType="VARCHAR" property="logo" />
<result column="islogo" jdbcType="INTEGER" property="islogo" />
</resultMap>
<sql id="whereClause">
<isNotNull property="map.boardname"> and boardname like #map.boardname#</isNotNull>
<isNotNull property="islogo"> and islogo=#islogo#</isNotNull>
</sql>
<select id="selectLinkByPrimaryKey" parameterClass="link" resultMap="LinkResult" cacheModel="oneDayCache">
select id, boardname, readme, url, logo, islogo from dv_bbslink where id = #id:INTEGER#
</select>
<select id="selectLinkList" parameterClass="link" resultMap="LinkResult">
select id, boardname, readme, url, logo, islogo from dv_bbslink where 1=1
<isParameterPresent>
<include refid="whereClause" />
</isParameterPresent>
<isNotNull property="row.count">limit 0, #row.count#</isNotNull>
</select>
<select id="selectLinkCount" parameterClass="link" resultClass="int">
select count(*) from dv_bbslink where 1=1
<isParameterPresent>
<include refid="whereClause" />
</isParameterPresent>
</select>
<select id="selectLinkPaginatedList" parameterClass="link" resultMap="LinkResult">
select id, boardname, readme, url, logo, islogo from dv_bbslink where 1=1
<isParameterPresent>
<include refid="whereClause" />
</isParameterPresent>
<isNotNull property="row.count">limit #row.first#, #row.count#</isNotNull>
</select>
<insert id="insertLink" parameterClass="link">
insert into dv_bbslink (boardname, readme, url, logo, islogo) values (
#boardname#,
#readme#,
#url#,
#logo#,
#islogo#)
<selectKey keyProperty="id" resultClass="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
<update id="updateLinkByPrimaryKey" parameterClass="link">
update dv_bbslink set
boardname = #boardname#,
readme = #readme#,
url = #url#,
logo =#logo#,
islogo = #islogo#
where id = #id:INTEGER#
</update>
<update id="updateLinkByPrimaryKeySelective" parameterClass="link">
</update>
<delete id="deleteLinkByPrimaryKey" parameterClass="link">
delete from dv_bbslink where id = #id#
</delete>
<delete id="deleteLink" parameterClass="link">
delete from dv_bbslink
<include refid="whereClause" />
</delete>
</sqlMap>
6、實例(MySQL)
一個論壇鏈接的表,分為LOGO鏈接,文字鏈接,有如下字段
6.1 數據庫表(dv_bbslink)
Id 自增ID(INTEGER)
Boardname 論壇名稱(VARCHAR)
Readme 說明(VARCHAR)
url 鏈接地址(VARCHAR)
logo LOGO圖片地址(VARCHAR)
islogo 是否是LOGO鏈接(INTEGER)
6.2 寫一個Domain(POJO,Model)
Link.java
private Integer id;
private String boardname;
private String readme;
private String url;
private String logo;
private Integer islogo;
//getters and setters
6.3 寫接口(LinkDao)
常用接口
根據業務邏輯生成特定的接口
LinkDao.java
publicinterface LinkDao {
Integer insertLink(Link link);
int updateLinkByPrimaryKey(Link link);
int updateLinkByPrimaryKeySelective(Link link);
int deleteLink(Link link);
int deleteLinkByPrimaryKey(Integer id);
List selectLinkList(Link link);
List selectLinkPaginatedList(Link link);
Link selectLinkByPrimaryKey(Integer id);
Integer selectLinkCount(Link link);
}
6.4 寫實現(LinkDaoSqlMapImpl)
public class LinkDaoSqlMapImpl extends SqlMapClientDaoSupport implements LinkDao {
public int deleteLink(Link link) {
int rows = super.getSqlMapClientTemplate().delete("deleteLink", link);
return rows;
}
public Integer insertLink(Link link) {
Object newKey = super.getSqlMapClientTemplate().insert("insertLink", link);
return (Integer) newKey;
}
public Link selectLinkByPrimaryKey(Integer id) {
Link key = new Link();
key.setId(id);
Link record = (Link) super.getSqlMapClientTemplate().queryForObject("selectLinkByPrimaryKey", key);
return record;
}
public Integer selectLinkCount(Link link) {
return (Integer) super.getSqlMapClientTemplate().queryForObject("selectLinkCount", link);
}
public List selectLinkList(Link link) {
return (List) super.getSqlMapClientTemplate().queryForList("selectLinkList", link);
}
public List selectLinkPaginatedList(Link link) {
return (List) super.getSqlMapClientTemplate().queryForList("selectLinkPaginatedList", link);
}
public int updateLinkByPrimaryKey(Link link) {
int rows = getSqlMapClientTemplate().update("updateLinkByPrimaryKey", link);
return rows;
}
public int updateLinkByPrimaryKeySelective(Link link) {
int rows = getSqlMapClientTemplate().update("updateLinkByPrimaryKeySelective", link);
return rows;
}
public int deleteLinkByPrimaryKey(Integer id) {
int rows = super.getSqlMapClientTemplate().delete("deleteLinkByPrimaryKey", id);
return rows;
}
}
6.5配置SQL Map
分析SQL Map 文件
6.7 配置 Spring Struts,寫Action, View,OK。
此討論在本文范圍外
7.其它
7.1 學習資源
wiki
faq
maillist
jpetstore 5.0
Spring包里也有個JPetStore 建議學習
7.2 自動化工具
容易使用,三步:
一、下載eclipse plug in
二、新建并配置一個abatorConfig.xml
三、生成model,sqlmap, dao和daoImpl
最后一步,加工它生成的代碼。
再一步,喝咖啡
8 名人名言
if you are starting a new project and you're in full control of your object model and database design, Hibernate is a good choice of O/R tool.
Clinton Begin
if you are accessing any 3rd party databases (e.g. vendor supplied), or you're working with a legacy database, or even just a really poorly designed database, then an O/R mapper might not be capable of handling the situation. That's were an SQL Mapper comes in handy
Clinton Begin
In the end the choice is yours and nobody can tell you what the right one is, Trust only yourself, draw your own conclusions and do lots of testing!