Ibatis+MySql實例

1. 介紹

       Ibatis是開源的持久層框架。它的核心是SqlMap,將實體Bean跟關係數據庫進行映射,將業務代碼和SQL語句的書寫進行分開,方便管理。Ibatis是“半自動”的ORM持久層框架。這裏的“半自動化”,是相對Hibernate等提供了全面的數據庫封裝機制的“全自動化”ORM 實現而言,“全自動”ORM 實現了 POJO 和數據庫表之間的映射,以及 SQL 的自動生成和執行。而iBATIS 的着力點,則在於POJO 與 SQL之間的映射關係。也就是說,iBATIS並不會爲程序員在運行期自動生成 SQL 執行。具體的 SQL 需要程序員編寫,然後通過映射配置文件,將SQL所需的參數,以及返回的結果字段映射到指定 POJO。

2. 前提

    1) 安裝了MySql數據庫;

    2) 將以下Jar包加入工程的classpath:commons-logging-1.0.4.jar、ibatis-2.3.0.677.jar、mysql-connector-java-5.0.3-bin.jar。

3. 實例

 3.1 在MySql數據庫中創建數據庫

  1. #############################################################################################  
  2. CREATE DATABASE MYDB;  
  3. use MYDB;  
  4.   
  5. Drop TABLE IF EXISTS `MYDB`.`student`;  
  6. Create TABLE `MYDB`.`student` (  
  7. `namevarchar(40) NOT NULL,  
  8. `psw` varchar(10) NOT NULL,  
  9. `enabled` boolean  
  10. );  
  11. insert into student values("lanp","lanpiao",true);  
  12. insert into student values("ph","ph",true);  
  13. insert into student values("wxh","wxh",true);  

 3.2 書寫實體Bean:Student.java

  1. package com.lanp.beans;  
  2.   
  3. /** 
  4.  * Student Bean 
  5.  * @author LanP 
  6.  * @since 2011-11-27 15:36 
  7.  * @version V1.0 
  8.  */  
  9. public class Student {  
  10.     private String name;  
  11.     private String psw;  
  12.     private Boolean enabled;  
  13.       
  14.     public String getName() {  
  15.         return name;  
  16.     }  
  17.     public void setName(String name) {  
  18.         this.name = name;  
  19.     }  
  20.     public String getPsw() {  
  21.         return psw;  
  22.     }  
  23.     public void setPsw(String psw) {  
  24.         this.psw = psw;  
  25.     }  
  26.     public Boolean getEnabled() {  
  27.         return enabled;  
  28.     }  
  29.     public void setEnabled(Boolean enabled) {  
  30.         this.enabled = enabled;  
  31.     }  
  32. }  

 3.3 配置數據庫的屬性文件:mysql.properties

  1. mysql.driver = com.mysql.jdbc.Driver  
  2. mysql.url = jdbc:mysql://localhost:3306/MYDB  
  3. mysql.username = root  
  4. mysql.password = 157891  

 3.4 SqlMap配置文件:sqlMapConfig.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE sqlMapConfig        
  3.     PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"        
  4.     "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">  
  5. <sqlMapConfig>  
  6.     <!-- Properties屬性配置文件,加載數據庫連接信息 -->  
  7.     <properties resource="mysql.properties"/>  
  8.    
  9.   <settings   
  10.     cacheModelsEnabled="true"      
  11.     enhancementEnabled="true"      
  12.     lazyLoadingEnabled="true"      
  13.     errorTracingEnabled="true"      
  14.     maxRequests="32"          
  15.     maxSessions="10"          
  16.     maxTransactions="5"          
  17.     useStatementNamespaces="false"   
  18.     />   
  19.     <!-- 配置Ibatis事務管理,使用JDBC事務類型,數據源使用Simple類型 -->  
  20.     <transactionManager type="JDBC">  
  21.         <dataSource type="SIMPLE">  
  22.             <property name="JDBC.Driver" value="${mysql.driver}"/>  
  23.             <property name="JDBC.ConnectionURL" value="${mysql.url}"/>  
  24.             <property name="JDBC.Username" value="${mysql.username}"/>  
  25.             <property name="JDBC.Password" value="${mysql.password}"/>  
  26.         </dataSource>  
  27.     </transactionManager>   
  28.     <!-- 配置Ibatis要使用的SqlMap文件信息 -->  
  29.     <sqlMap resource="com/lanp/beans/student.xml"/>  
  30. </sqlMapConfig>  


 3.5 student實體Bean的映射配置:student.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE sqlMap        
  3.     PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"        
  4.     "http://ibatis.apache.org/dtd/sql-map-2.dtd">  
  5. <sqlMap>  
  6.     <!-- 爲Person類設置一個別名 -->  
  7.     <typeAlias alias="student" type="com.lanp.beans.Student"/>  
  8.       
  9.     <!-- 配置表和實體Bean之間的映射關係 -->  
  10.     <resultMap id="studentMap" class="com.lanp.beans.Student">  
  11.         <result property="name" column="name"/>  
  12.         <result property="psw" column="psw"/>  
  13.         <result property="enabled" column="enabled"/>  
  14.     </resultMap>  
  15.       
  16.     <insert id="insertStudent" parameterClass="student">  
  17.         <![CDATA[ 
  18.             insert into student values(#name#,#psw#,#enabled#); 
  19.         ]]>  
  20.     </insert>  
  21.       
  22.     <!-- 查看特定用戶 -->  
  23.     <select id="queryStudentById" parameterClass="string" resultMap="studentMap">  
  24.         <![CDATA[ 
  25.             SELECT * FROM STUDENT WHERE NAME=#name# 
  26.         ]]>  
  27.     </select>  
  28.       
  29.     <!-- 查看所有的用戶 -->  
  30.     <select id="queryAllStudents" resultMap="studentMap">  
  31.         <![CDATA[ 
  32.             SELECT * FROM STUDENT 
  33.         ]]>  
  34.     </select>  
  35. </sqlMap>  


 3.6 測試類:TestStudent.java

  1. package com.lanp.beans;  
  2.   
  3. import java.io.Reader;  
  4. import java.util.List;  
  5.   
  6. import com.ibatis.common.resources.Resources;  
  7. import com.ibatis.sqlmap.client.SqlMapClient;  
  8. import com.ibatis.sqlmap.client.SqlMapClientBuilder;  
  9.   
  10. /** 
  11.  * 測試Ibatis 
  12.  * @author LanP 
  13.  * @since 2011-11-27 15:36 
  14.  * @version V1.0 
  15.  */  
  16. public class TestStudent {  
  17.   
  18.     public static void main(String[] args) {  
  19.   
  20.         String resource = "sqlMapConfig.xml";  
  21.         try {  
  22.             //讀取配置文件  
  23.             Reader reader = Resources.getResourceAsReader(resource);  
  24.             //得到SqlMapClient  
  25.             SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);  
  26.               
  27.             //新增學生信息  
  28.             insertStudent(sqlMap);  
  29.               
  30.             //查看全部的學生  
  31.             queryAllStudents(sqlMap);  
  32.               
  33.             //查看特定的學生  
  34.             queryStudentByName(sqlMap);  
  35.         } catch(Exception e){}  
  36.     }  
  37.       
  38.     /** 
  39.      * 根據學生的名字查詢特定的學生信息 
  40.      * @param sqlMap 
  41.      */  
  42.     private static void queryStudentByName(SqlMapClient sqlMap) {  
  43.         try {  
  44.             System.out.println("--------------查詢特定的學生信息-------------------------");  
  45.             Student stu = (Student)sqlMap.queryForObject("queryStudentById""lanp");  
  46.             if(null != stu) {  
  47.                 System.out.println("== 學生名字: " + stu.getName() + " ,學生密碼: " + stu.getPsw() + " ==");  
  48.             }  
  49.         } catch(Exception e){}  
  50.     }  
  51.   
  52.     /** 
  53.      * 顯示所有學生的信息 
  54.      * @param sqlMap 
  55.      */  
  56.     @SuppressWarnings("unchecked")  
  57.     private static void queryAllStudents(SqlMapClient sqlMap) {  
  58.         try {  
  59.             System.out.println("--------------查詢所有的學生信息-------------------------");  
  60.             List<Student> students = sqlMap.queryForList("queryAllStudents");  
  61.             if(null != students && students.size()>0) {  
  62.                 for(int i=0; i<students.size(); i++) {  
  63.                     Student student = students.get(i);  
  64.                     System.out.println("== 學生名字: " + student.getName() + " ,學生密碼: " + student.getPsw() +" ==");  
  65.                 }  
  66.             }  
  67.         } catch(Exception e){}  
  68.     }  
  69.   
  70.   
  71.   
  72.     /** 
  73.      * 新增學生信息 
  74.      * @param sqlMap 
  75.      */  
  76.     private static void insertStudent(SqlMapClient sqlMap) {  
  77.         try {  
  78.             System.out.println("--------------新增學生信息-------------------------");  
  79.             Student student = new Student();  
  80.             student.setName("xinh");  
  81.             student.setPsw("123");  
  82.             student.setEnabled(true);  
  83.             //開始Ibatis事務  
  84.             sqlMap.startTransaction();  
  85.             sqlMap.insert("insertStudent", student);  
  86.             //結束IBatis事務  
  87.             sqlMap.commitTransaction();  
  88.         } catch(Exception e){}  
  89.     }  
  90.       
  91. }  
發佈了31 篇原創文章 · 獲贊 2 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章