`

ibatis入门实例讲解(转)

阅读更多

之前大家上网的ibatis官方网站:http://www.ibatis.com现在已经不再存在了,已经被MyBatis所替代http://www.mybatis.org/,我现在使用了还是之前的ibatis2.3.4,所以这个例子也是针对2.3.4版本讲解的

首先呢,打开资源包,可以看到里面有一个simple_exzample的文件夹,在MyEclipse8.5中新建一个JAVA项目,将刚才的文件夹中内容复制到项目SRC下,这样的话呢,可以看到这样一个目录



 这个MyTest是我后来加上的测试实实例,当然这些代码还不足以让程序测试出结果来

 看看ibatis的SQL语句配置类MySqlMapConfig.xml

Xml代码  收藏代码
  1. <span style="font-size: medium;"><?xml version="1.0" encoding="UTF-8" ?>  
  2.   
  3. <!DOCTYPE sqlMapConfig        
  4.     PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"        
  5.     "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">  
  6.   
  7. <sqlMapConfig>  
  8.   
  9.   <!-- Configure a built-in transaction manager.  If you're using an   
  10.        app server, you probably want to use its transaction manager   
  11.        and a managed datasource -->  
  12.   <transactionManager type="JDBC" commitRequired="false">  
  13.     <dataSource type="SIMPLE">  
  14.       <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>  
  15.       <property name="JDBC.ConnectionURL" value="jdbc:mysql://127.0.0.1:3306/ibatis"/>  
  16.       <property name="JDBC.Username" value="root"/>  
  17.       <property name="JDBC.Password" value="root"/>  
  18.     </dataSource>  
  19.   </transactionManager>  
  20.   
  21.   <!-- List the SQL Map XML files. They can be loaded from the   
  22.        classpath, as they are here (com.domain.data...) -->  
  23.   <sqlMap resource="com/mydomain/data/Account.xml"/>  
  24.   <!-- List more here...  
  25.   <sqlMap resource="com/mydomain/data/Order.xml"/>  
  26.   <sqlMap resource="com/mydomain/data/Documents.xml"/>  
  27.   -->  
  28.   
  29. </sqlMapConfig>  
  30. </span>  

 

这里我修改了下数据源为jdbc形式的,使用的是MySQL数据库,所以要添加数据库驱动包,还有ibatis核心包,在看看数据库表该怎么建立,这得查看下Account.xml了

Xml代码  收藏代码
  1. <span style="font-size: medium;"><?xml version="1.0" encoding="UTF-8" ?>  
  2.   
  3. <!DOCTYPE sqlMap        
  4.     PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"        
  5.     "http://ibatis.apache.org/dtd/sql-map-2.dtd">  
  6.   
  7. <sqlMap namespace="Account">  
  8.   
  9.   <!-- Use type aliases to avoid typing the full classname every time. -->  
  10.   <typeAlias alias="Account" type="com.mydomain.domain.Account"/>  
  11.   
  12.   <!-- Result maps describe the mapping between the columns returned  
  13.        from a query, and the class properties.  A result map isn't  
  14.        necessary if the columns (or aliases) match to the properties   
  15.        exactly. -->  
  16.   <resultMap id="AccountResult" class="Account">  
  17.     <result property="id" column="ACC_ID"/>  
  18.     <result property="firstName" column="ACC_FIRST_NAME"/>  
  19.     <result property="lastName" column="ACC_LAST_NAME"/>  
  20.     <result property="emailAddress" column="ACC_EMAIL"/>  
  21.   </resultMap>  
  22.   
  23.   <!-- Select with no parameters using the result map for Account class. -->  
  24.   <select id="selectAllAccounts" resultMap="AccountResult">  
  25.     select * from ACCOUNT  
  26.   </select>  
  27.   
  28.   <!-- A simpler select example without the result map.  Note the   
  29.        aliases to match the properties of the target result class. -->  
  30.   <select id="selectAccountById" parameterClass="int" resultClass="Account">  
  31.     select  
  32.       ACC_ID as id,  
  33.       ACC_FIRST_NAME as firstName,  
  34.       ACC_LAST_NAME as lastName,  
  35.       ACC_EMAIL as emailAddress  
  36.     from ACCOUNT  
  37.     where ACC_ID = #id#  
  38.   </select>  
  39.      
  40.   <!-- Insert example, using the Account parameter class -->  
  41.   <insert id="insertAccount" parameterClass="Account">  
  42.     insert into ACCOUNT (  
  43.       ACC_FIRST_NAME,  
  44.       ACC_LAST_NAME,  
  45.       ACC_EMAIL  
  46.     )values (  
  47.       #firstName#, #lastName#, #emailAddress#  
  48.     )  
  49.   </insert>  
  50.   
  51.   <!-- Update example, using the Account parameter class -->  
  52.   <update id="updateAccount" parameterClass="Account">  
  53.     update ACCOUNT set  
  54.       ACC_FIRST_NAME = #firstName#,  
  55.       ACC_LAST_NAME = #lastName#,  
  56.       ACC_EMAIL = #emailAddress#  
  57.     where  
  58.       ACC_ID = #id#  
  59.   </update>  
  60.   
  61.   <!-- Delete example, using an integer as the parameter class -->  
  62.   <delete id="deleteAccountById" parameterClass="int">  
  63.     delete from ACCOUNT where ACC_ID = #id#  
  64.   </delete>  
  65.   
  66. </sqlMap></span>  

 上面的<ResultMap>标签中有指定每个Account属性对应的数据库的列名,所以就新建数据库了

 这样数据建立完成后,我们就可以测试了,这回就用到了SimpleExample.java类了

Java代码  收藏代码
  1. <span style="font-size: medium;">package com.mydomain.data;  
  2.   
  3. import com.ibatis.sqlmap.client.SqlMapClient;  
  4. import com.ibatis.sqlmap.client.SqlMapClientBuilder;  
  5. import com.ibatis.common.resources.Resources;  
  6. import com.mydomain.domain.Account;  
  7.   
  8. import java.io.Reader;  
  9. import java.io.IOException;  
  10. import java.util.List;  
  11. import java.sql.SQLException;  
  12.   
  13. /** 
  14.  * This is not a best practices class.  It's just an example 
  15.  * to give you an idea of how iBATIS works.  For a more complete 
  16.  * example, see JPetStore 5.0 at http://www.ibatis.com. 
  17.  */  
  18. public class SimpleExample {  
  19.   
  20.   /** 
  21.    * SqlMapClient instances are thread safe, so you only need one. 
  22.    * In this case, we'll use a static singleton.  So sue me.  ;-) 
  23.    */  
  24.   private static SqlMapClient sqlMapper;  
  25.   
  26.   /** 
  27.    * It's not a good idea to put code that can fail in a class initializer, 
  28.    * but for sake of argument, here's how you configure an SQL Map. 
  29.    */  
  30.   static {  
  31.     try {  
  32.       Reader reader = Resources.getResourceAsReader("com/mydomain/data/MySqlMapConfig.xml");  
  33.       sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);  
  34.       reader.close();   
  35.     } catch (IOException e) {  
  36.       // Fail fast.  
  37.       throw new RuntimeException("Something bad happened while building the SqlMapClient instance." + e, e);  
  38.     }  
  39.   }  
  40.   
  41.   public static List selectAllAccounts () throws SQLException {  
  42.     return sqlMapper.queryForList("selectAllAccounts");  
  43.   }  
  44.   
  45.   public static Account selectAccountById  (int id) throws SQLException {  
  46.     return (Account) sqlMapper.queryForObject("selectAccountById", id);  
  47.   }  
  48.   
  49.   public static void insertAccount (Account account) throws SQLException {  
  50.     sqlMapper.insert("insertAccount", account);  
  51.   }  
  52.   
  53.   public static void updateAccount (Account account) throws SQLException {  
  54.     sqlMapper.update("updateAccount", account);  
  55.   }  
  56.   
  57.   public static void deleteAccount (int id) throws SQLException {  
  58.     sqlMapper.delete("deleteAccountById", id);  
  59.   }  
  60.   
  61. }  
  62. </span>  

  像上面的增删改查中用到的代替SQL语句的映射KEY,也是可以加上相应的XML文件的配置名称的,如: return sqlMapper.queryForList("Account.selectAllAccounts")那么这个Account就是

Account.xml的名称了

真正想看到测试结果得另写个JUNIT测试类,添加junit的jar包,这里我写了MyTest.java

Java代码  收藏代码
  1. <span style="font-size: medium;">package com.mydomain.data;  
  2.   
  3. import java.sql.SQLException;  
  4. import java.util.Arrays;  
  5. import java.util.Collections;  
  6. import java.util.List;  
  7.   
  8. import org.junit.Test;  
  9.   
  10. import com.mydomain.domain.Account;  
  11.   
  12. public class MyTest {  
  13.     @Test  
  14.     public void selectAllAccounts(){  
  15.         try {  
  16.             List list=SimpleExample.selectAllAccounts();  
  17.             System.out.println(Arrays.toString(list.toArray()));  
  18.         } catch (SQLException e) {  
  19.             // TODO Auto-generated catch block  
  20.             e.printStackTrace();  
  21.         }  
  22.     }  
  23.       
  24.     public void selectAccountById(){  
  25.         try {  
  26.             Account account=SimpleExample.selectAccountById(1);  
  27.             System.out.println(account);  
  28.         } catch (SQLException e) {  
  29.             // TODO Auto-generated catch block  
  30.             e.printStackTrace();  
  31.         }  
  32.     }  
  33.       
  34.     public void insertAccount(){  
  35.         Account account=new Account();  
  36.         account.setFirstName("tom");  
  37.         account.setLastName("jam");  
  38.         account.setEmailAddress("china");  
  39.         try {  
  40.             SimpleExample.insertAccount(account);  
  41.         } catch (SQLException e) {  
  42.             // TODO Auto-generated catch block  
  43.             e.printStackTrace();  
  44.         }  
  45.     }  
  46.       
  47.     public void updateAccount(){  
  48.         try {  
  49.             Account account=SimpleExample.selectAccountById(2);  
  50.             account.setFirstName("gates");  
  51.             SimpleExample.updateAccount(account);  
  52.         } catch (SQLException e) {  
  53.             // TODO Auto-generated catch block  
  54.             e.printStackTrace();  
  55.         }  
  56.           
  57.     }  
  58.       
  59.     public void deleteAccount(){  
  60.         try {  
  61.             SimpleExample.deleteAccount(1);  
  62.         } catch (SQLException e) {  
  63.             e.printStackTrace();  
  64.         }  
  65.     }  
  66.       
  67. }  
  68. </span>  

 

怎么样,ibatis也不是很难吧,将所有的SQL语句统一管理起来,十分方便,对于写复杂的SQL语句也可以直接来写

 

 顺便介绍下MyBatis

MyBatis来源于iBATIS,iBATIS是一个由Clinton Begin在2001年发起的开放源代码项目,iBATIS一词来源于“internet”和“abatis”的组合。该项目最初侧重于密码软件的开发,现在是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO),它是著名的ORM开发框架,分为Java和.NET版本,有着众多的追随者。 

iBATIS更名为MyBatis并迁移到Google Code,此次项目迁移后,将启用新的网站http://www.mybatis.org/,由于目前只是改了名字,因此仍然可直接浏览iBatis的文档。 

MyBatis开发团队希望脱离Apache而独立发展,并保证不会修改授权协议(Apache License)、代码完全兼容、包名不会更改、也不会删除 Apache站上的任何相关资源。 

改名后的第一次版本MyBatis 3.0.1已经发布,基于iBatis 3.0版本,该版本非常稳定,已经有很多用户使用了数周时间,修复了一些小bug。欲下载 MyBatis 3.0.1请到它新的网站http://www.mybatis.org/。 目前版本是3.0.2

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics