posts - 297,  comments - 1618,  trackbacks - 0
                原文出處:http://blog.csdn.net/tenwang1977/archive/2004/08/17/76972.aspx
              

          本文章將從一個(gè)Ibatis的具體示例,幫助你快速了解IBatis框架。

          一個(gè)簡(jiǎn)單的IBatis應(yīng)用包含以下基本步驟:

          一、 配置文件
          1. 配置SqlMapConfig.properties文件

          2. 配置SqlMapConfig.xml文件

          3. 配置SqlMap.xml文件(可能有多個(gè)文件,一般情況下,可以一個(gè)表對(duì)應(yīng)一個(gè)SqlMap.xml文件,文件名稱可以與表名相同)

          注意:上面所述的SqlMapConfig.xml文件必須在類路徑中,SqlMapConfig.properties和SqlMap.xml文件可以在類路徑中,也可以不在類路徑中。當(dāng)SqlMapConfig.properties和SqlMap.xml文件不在類路徑中的時(shí)候,配置也不同,在本文中,這三個(gè)文件都放在類路徑中。

          二、 程序調(diào)用
          1. 初始化SqlMapClient對(duì)象。

          2. 運(yùn)行Sql語句:你可以調(diào)用SqlMapClient對(duì)象的queryfor...()、insert()、update()、delete()來分別執(zhí)行select、insert、update和delete操作。

          好了,下面我們結(jié)合實(shí)例進(jìn)行講解:
          三、實(shí)例:

          下面的例子是以mysql為例進(jìn)行說明,建立了一個(gè)author表,為了方便調(diào)試代碼,你可以將ibatis-common-2.jar、ibatis-dao-2.jar、ibatis-sqlmap-2.jar和lib目錄下的所有的jar都加載到你的程序中,在后續(xù)的文章中,將會(huì)說明每個(gè)Jar的用途。

          (一) 創(chuàng)建數(shù)據(jù)庫和表
          創(chuàng)建一個(gè)名字為IBatisExample的數(shù)據(jù)庫
          CREATE TABLE author (
            auth_id int(8) NOT NULL auto_increment,
            auth_name varchar(100) NOT NULL default '',
            auth_age int(3) NOT NULL default '0',
            auth_tel varchar(100) NOT NULL default '',
            auth_address varchar(100) NOT NULL default '',
            PRIMARY KEY  (auth_id)
          ) TYPE=MyISAM;
          INSERT INTO author VALUES (1, '作者一', 30, '025-12345678', '南京');
          INSERT INTO author VALUES (2, '作者二', 30, '025-12345678', '南京');

          (二) 配置文件

          1. 配置SqlMapConfig.properties文件
          文件內(nèi)容:
          driver=org.gjt.mm.mysql.Driver
          url=jdbc:mysql://192.168.0.26:3306/IBatisExample?useUnicode=true&characterEncoding=GB2312
          username=root
          password=123456

          2. 配置SqlMapConfig.xml文件
          文件內(nèi)容:
          <?xml version="1.0" encoding="UTF-8" ?>
          <!DOCTYPE sqlMapConfig
          PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
          " <!-- Always ensure to use the correct XML header as above! -->
          <sqlMapConfig>
          <!-- The properties (name=value) in the file specified here can be used placeholders in this config
          file (e.g. “${driver}”. The file is relative to the classpath and is completely optional. -->
          <properties resource="SqlMapConfig.properties" />
          <!-- These settings control SqlMapClient configuration details, primarily to do with transaction
          management. They are all optional (more detail later in this document). -->
          <settings
          cacheModelsEnabled="true"
          enhancementEnabled="true"
          lazyLoadingEnabled="true"
          maxRequests="32"
          maxSessions="10"
          maxTransactions="5"
          useStatementNamespaces="false"
          />

          <!-- Configure a datasource to use with this SQL Map using SimpleDataSource.
          Notice the use of the properties from the above resource -->
          <transactionManager type="JDBC" >
          <dataSource type="SIMPLE">
          <property name="JDBC.Driver" value="${driver}"/>
          <property name="JDBC.ConnectionURL" value="${url}"/>
          <property name="JDBC.Username" value="${username}"/>
          <property name="JDBC.Password" value="${password}"/>
          <property name="JDBC.DefaultAutoCommit" value="true" />
          <property name="Pool.MaximumActiveConnections" value="10"/>
          <property name="Pool.MaximumIdleConnections" value="5"/>
          <property name="Pool.MaximumCheckoutTime" value="120000"/>
          <property name="Pool.TimeToWait" value="500"/>
          <property name="Pool.PingQuery" value="select 1 from author"/>
          <property name="Pool.PingEnabled" value="false"/>
          <property name="Pool.PingConnectionsOlderThan" value="1"/>
          <property name="Pool.PingConnectionsNotUsedFor" value="1"/>
          </dataSource>
          </transactionManager>
          <!-- Identify all SQL Map XML files to be loaded by this SQL map. Notice the paths
          are relative to the classpath. For now, we only have one… -->
          <sqlMap resource="com/ibatis/sqlmap/author.xml" />
          </sqlMapConfig>

          3. 配置SqlMap.xml文件
          這里我們命名為author.xml

          <?xml version="1.0" encoding="UTF-8" ?>
          <!DOCTYPE sqlMap
          PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
          "
          <sqlMap namespace="Author">
          <typeAlias alias="Author" type="com.ibatis.beans.Author" />

          <select id="getAuthor" parameterClass="int" resultClass="Author">
           SELECT auth_id as id,auth_name as name,auth_age as age,auth_tel as telephone,auth_address as address FROM author WHERE auth_id = #id#
          </select>

          <statement id="getAllAuthor" resultMap="authorResult">
           SELECT * FROM author
          </statement>

          <insert id="insertAuthor" parameterMap="authorParameter">
           INSERT INTO author (auth_name,auth_age,auth_tel,auth_address) VALUES (?,?,?,?)
          </insert>

          <update id="updateAuthor" parameterClass="Author">
           UPDATE author set auth_name=#name# WHERE auth_id = #id#
          </update>

          <delete id="deleteAuthor" parameterClass="int">
           delete from author WHERE auth_id = #id#
          </delete>

          </sqlMap>

          (三) 程序調(diào)用
          由于源代碼很長(zhǎng),所以這里我只給出一些簡(jiǎn)單的程序調(diào)用方法,所以如果有人想要源代碼的話,可以留下你的郵箱。
          1. 初始化一個(gè)SqlMapClient對(duì)象,代碼如下:
          public class SqlMapConf
          {
              private static SqlMapClient sqlMapClient;
              static
           {
            try
            {
                System.out.println("sqlMapClient initing.....");
             String resource = "SqlMapConfig.xml";
             Reader reader = Resources.getResourceAsReader (resource);
             sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
            }
            catch (Exception e)
            {
             e.printStackTrace();
             throw new RuntimeException ("Error initializing MyAppSqlConfig class. Cause: " +e);
            }
           }
              public static SqlMapClient getInstance()
              {
                  return sqlMapClient;
              } 
          }

          2. 然后要為Author表寫一個(gè)bean,代碼如下:
          public class Author
          {
              private int id;
              private int age;
              private String name;  
              private String address;
              private String telephone;
             
              public int getId()
              {
                  return id;
              }
              public void setId(int id)
              {
                  this.id=id;
              }
              public int getAge()
              {
                  return age;
              }
              public void setAge(int age)
              {
                  this.age=age;
              }
              public String getName()
              {
                  return name;
              }
              public void setName(String name)
              {
                  this.name=name;
              }
             
              public String getAddress()
              {
                  return address;
              }
              public void setAddress(String address)
              {
                  this.address=address;
              }
              public String getTelephone()
              {
                  return telephone;
              }
              public void setTelephone(String telephone)
              {
                  this.telephone=telephone;
              }
          }

          3. 程序調(diào)用:
          這里將只示范一下getAuthor、insertAuthor1、updateAuthor和deleteAuthor的方法。
          首先應(yīng)該得到一個(gè)SqlMapClient實(shí)例:
          SqlMapClient sqlMapClient = SqlMapConf.getInstance();

          (1) getAuthor:
           Author author = (Author)sqlMapClient.queryForObject("getAuthor", new Integer(1));
          (2) getAllAuthor
           List authorList = (List)sqlMapClient.queryForList("getAllAuthor", null);
          (3) insertAuthor:
           Author author = new Author();
           author.setName("作者三");
           author.setAge(31);
           author.setAddress("南京");
           author.setTelephone("025-987654321");
           sqlMapClient.insert(operaName, author);
          (4) updateAuthor
           Author author = new Author();
           author.setName("Updated");
           author.setId(authorID);
           sqlMapClient.update(operaName, author);       
          (5) deleteAuthor
           sqlMapClient.delete("deleteAuthor", new Integer(authorID));

          這里只是做一個(gè)簡(jiǎn)單的例子,希望能夠幫助快速的入門,而并沒有對(duì)IBatis的原理進(jìn)行剖析,不過通過這幾個(gè)調(diào)用,我想你可能能夠猜到IBatis的一部分運(yùn)作原理了,關(guān)于IBatis的原理以及高級(jí)應(yīng)用,請(qǐng)關(guān)注后續(xù)文章。



          FeedBack:
          # re: [轉(zhuǎn)載]Ibatis2.0使用說明(一)——入門實(shí)例篇
          2007-10-24 21:46 | 青菜貓(孫宇)
          這個(gè)我也用了,感覺可以,的,不知道你對(duì)多表查詢,更新有什么建議..  回復(fù)  更多評(píng)論
            
          # re: [轉(zhuǎn)載]Ibatis2.0使用說明(一)——入門實(shí)例篇
          2007-10-27 19:26 | tanlei
          女程序員!稀罕!頂一個(gè)!  回復(fù)  更多評(píng)論
            
          # re: [轉(zhuǎn)載]Ibatis2.0使用說明(一)——入門實(shí)例篇
          2008-05-12 10:58 | 開機(jī)
          (1)String resource = "SqlMapConfig.xml";
          Reader reader = Resources.getResourceAsReader (resource);
          sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
          中:
          為什么不直接用 sqlMapClient = SqlMapClientBuilder.buildSqlMapClient("SqlMapConfig.xml");
          (2)像SqlMapConfig.xml,author.xml,author bean這樣的要是可以根據(jù)數(shù)據(jù)生成就好了,就像hibernate那樣,以后再根據(jù)需要改。因?yàn)檫@樣?xùn)|東本身就是重復(fù)性的工作。不知道有沒有這樣的插件?  回復(fù)  更多評(píng)論
            

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          <2007年10月>
          30123456
          78910111213
          14151617181920
          21222324252627
          28293031123
          45678910

                生活將我們磨圓,是為了讓我們滾得更遠(yuǎn)——“圓”來如此。
                我的作品:
                玩轉(zhuǎn)Axure RP  (2015年12月出版)
                

                Power Designer系統(tǒng)分析與建模實(shí)戰(zhàn)  (2015年7月出版)
                
               Struts2+Hibernate3+Spring2   (2010年5月出版)
               

          留言簿(263)

          隨筆分類

          隨筆檔案

          文章分類

          相冊(cè)

          關(guān)注blog

          積分與排名

          • 積分 - 2296332
          • 排名 - 3

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          主站蜘蛛池模板: 景宁| 家居| 长沙市| 铜川市| 高雄市| 蓬安县| 南康市| 望奎县| 长寿区| 松原市| 天台县| 保靖县| 拉孜县| 华蓥市| 比如县| 大方县| 儋州市| 玉环县| 邹平县| 肥城市| 石台县| 五莲县| 炎陵县| 漠河县| 衡水市| 莎车县| 新竹市| 贵港市| 呼和浩特市| 句容市| 长汀县| 同仁县| 临沂市| 科技| 涪陵区| 军事| 株洲市| 德江县| 元氏县| 六安市| 镇原县|