---
title: "iBATIS实现的一个例子"
author: "iammonster"
date: "2007-05-18T19:11:00Z"
tags: []
slug: "ibatis"
draft: false
lastmod: "2007-05-18T19:11:00Z"
id: 273306
url: "https://jiajun.iteye.com/blog/273306"
---

这里把我学习ibatis时候，一个实现的例子发上来，供参考。

工程目录结构如下：

![](http://p.blog.csdn.net/images/p_blog_csdn_net/ice_spar/gc1.gif)

//1、SQL MAP配置文件

SqlMapConfig.xml

&lt;?xml version="1.0" encoding="UTF-8" ?&gt;  
&lt;!DOCTYPE sqlMapConfig  
    PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"  
    "[http://www.ibatis.com/dtd/sql-map-config-2.dtd](http://www.ibatis.com/dtd/sql-map-config-2.dtd)"&gt;

&lt;sqlMapConfig&gt;   
   &lt;properties resource="com/study/xiaofeng/maps/SqlMapConfig.properties"/&gt;  
  &lt;settings cacheModelsEnabled="true"  
           enhancementEnabled="true"  
        lazyLoadingEnabled="true"  
        errorTracingEnabled="true"  
        maxRequests="32"  
        maxSessions="10"  
        maxTransactions="5"  
        useStatementNamespaces="false" /&gt;  
   
   
 &lt;transactionManager type="JDBC"&gt;  
  &lt;dataSource type="SIMPLE"&gt;  
   &lt;property name="JDBC.Driver" value="${driver}" /&gt;  
   &lt;property name="JDBC.ConnectionURL" value="${url}" /&gt;  
   &lt;property name="JDBC.Username" value="${username}" /&gt;  
   &lt;property name="JDBC.Password" value="${password}" /&gt;  
   &lt;property name="Pool.MaximumActiveConnections" value="10" /&gt;  
   &lt;property name="Pool.MaximumIdleConnections" value="5" /&gt;  
   &lt;property name="Pool.MaximumCheckoutTime" value="120000" /&gt;  
   &lt;property name="Pool.TimeToWait" value="500" /&gt;  
   &lt;property name="Pool.PingQuery" value="select 1 from sample" /&gt;  
   &lt;property name="Pool.PingEnabled" value="false" /&gt;  
   &lt;property name="Pool.PingConnectionsOlderThan" value="1" /&gt;  
   &lt;property name="Pool.PingConnectionsNotUsedFor" value="1" /&gt;  
  &lt;/dataSource&gt;  
 &lt;/transactionManager&gt;

&lt;!--  
&lt;transactionManager type="JTA" &gt;  
&lt;property name="UserTransaction"  
value="java:comp/env/jdbc/framework"/&gt;  
&lt;dataSource type="JNDI"&gt;  
&lt;property name="DataSource"  
value="java:comp/env/jdbc/ibatistest"/&gt;  
&lt;/dataSource&gt;  
&lt;/transactionManager&gt;

&lt;transactionManager type="JDBC" &gt;  
&lt;dataSource type="JNDI"&gt;  
&lt;property name="DataSource"  
value="java:comp/env/jdbc/ibatistest"/&gt;  
&lt;/dataSource&gt;  
&lt;/transactionManager&gt;  
\--&gt;  
 &lt;sqlMap resource="com/study/xiaofeng/maps/person.xml" /&gt;  
&lt;/sqlMapConfig&gt;

 

//2、SQL Map配置文件拥有唯一的&lt;properties&gt;元素，这样做后，在属性文件中定义的属性可以作为变量在SQL Map配置文件及其包含的所有SQL Map映射文件中引用

SqlMapConfig.xml

driver=com.microsoft.jdbc.sqlserver.SQLServerDriver  
url=jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=ibatistest;SelectMethod=Cursor;

username=xiaofeng  
password=xiaofeng

 

//3、SQL Map XML映射

person.xml

&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
&lt;!DOCTYPE sqlMap  
PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"  
"[http://www.ibatis.com/dtd/sql-map-2.dtd](http://www.ibatis.com/dtd/sql-map-2.dtd)"&gt;  
&lt;sqlMap namespace="Student"&gt;

&lt;typeAlias alias="student" type="com.study.xiaofeng.Student"/&gt;  
&lt;typeAlias alias="course" type="com.study.xiaofeng.Course"/&gt;  
&lt;typeAlias alias="intro" type="com.study.xiaofeng.Intro"/&gt;  
&lt;typeAlias alias="sc" type="com.study.xiaofeng.SC"/&gt;

&lt;resultMap id="get-student-result" class="student" &gt;  
&lt;result property="sno" column="Sno"/&gt;  
&lt;result property="sname" column="Sname"/&gt;  
&lt;result property="ssex" column="Ssex"/&gt;  
&lt;result property="sage" column="Sage"/&gt;  
&lt;result property="sdept" column="Sdept"/&gt;  
&lt;result property="sc" column="Sno" select="getSc"/&gt;  
&lt;result property="intro" column="Sno" select="getIntro"/&gt;

&lt;/resultMap&gt;  
&lt;resultMap id="get-course-result" class="course"&gt;  
&lt;result property="cno" column="Cno"/&gt;  
&lt;result property="cname" column="cname"/&gt;  
&lt;result property="ccredit" column="Ccredit"/&gt;  
&lt;/resultMap&gt;  
&lt;resultMap class="intro" id="get-intro-result"&gt;  
&lt;result property="sno" column="Sno"/&gt;  
&lt;result property="idescription" column="Idescription"/&gt;  
&lt;/resultMap&gt;  
&lt;!--  
&lt;resultMap id="get-sc-result" class="sc" &gt;  
&lt;result property="sno" column="Sno"/&gt;  
&lt;result property="cno" column="Cno"/&gt;  
&lt;result property="grade" column="Grade"/&gt;  
&lt;result property="course" column="Cno" select="getCourse"/&gt;  
&lt;/resultMap&gt;  
 --&gt;  
&lt;select id="getStudent" parameterClass="String" resultMap="get-student-result"&gt;  
select * from STUDENT  
WHERE  
Sname=#value#  
&lt;/select&gt;  
&lt;select id="getCourse" parameterClass="Integer" resultMap="get-course-result"&gt;  
select * from COURSE WHERE Cno=#value#  
&lt;/select&gt;  
&lt;select id="getIntro" parameterClass="Integer" resultMap="get-intro-result"&gt;  
select \*from INTRO WHERE Sno=#value#  
&lt;/select&gt;  
&lt;select id="getSc" parameterClass="Integer" resultClass="SC"&gt;  
select Cno,Grade  
from SC  
WHERE  
Sno=#sno#  
&lt;/select&gt;

&lt;insert id="insertStudent" parameterClass="student"&gt;  
INSERT INTO  
STUDENT (Sno,Sname,Ssex,Sage,Sdept)  
VALUES (#sno#,#sname#,#ssex#,#sage#,#sdept#)  
&lt;/insert&gt;  
&lt;update id="updateStudent" parameterClass="student"&gt;  
UPDATE STUDENT  
SET Sname= #sname#,  
Ssex= #ssex#,  
Sage=#sage#,  
Sdept=#sdept#  
WHERE Sno = #sno#  
&lt;/update&gt;  
&lt;delete id="deleteStudent" parameterClass="student"&gt;  
DELETE STUDENT  
WHERE Sno = #sno#  
&lt;/delete&gt;  
&lt;/sqlMap&gt;

 

 //４、AppSqlConfig.java

package com.study.xiaofeng;  
import com.ibatis.sqlmap.client.SqlMapClient;  
import java.io.Reader;  
import com.ibatis.common.resources.\*;  
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class AppSqlConfig {  
 private static final SqlMapClient sqlMap;  
 static {  
 try {  
 String resource ="com/study/xiaofeng/maps/SqlMapConfig.xml";  
 Reader reader = Resources.getResourceAsReader (resource);  
 sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);  
 } catch (Exception e) {  
  e.printStackTrace();  
  throw new RuntimeException ("Error initializing MyAppSqlConfig class. Cause: "+e);  
  }  
}  
public static SqlMapClient getSqlMapInstance () {  
   return sqlMap;  
  }  
}

//test.java

package com.study.xiaofeng;  
import com.ibatis.sqlmap.client.SqlMapClient;  
import java.sql.\*;  
import java.util.List;  
//JTA  
import javax.naming.InitialContext;  
import javax.transaction.UserTransaction;  
public class Test {  
    public static void update(int no,String name,String sex,int age,String dept){  
     com.ibatis.sqlmap.client.SqlMapClient client = null;  
     try{  
          client=new AppSqlConfig().getSqlMapInstance();  
       client.startTransaction();  
       Student student=new Student();  
       student.setSno(no);  
       student.setSname(name);  
       student.setSsex(sex);  
       student.setSage(age);  
       student.setSdept(dept);  
       client.update("updateStudent",student);  
       client.commitTransaction();  
     }catch(SQLException e){  
         System.out.println(e.getMessage());  
     }finally {  
   try {  
    client.endTransaction();  
   } catch (SQLException e) {  
    e.printStackTrace();  
   }  
  }  
    }  
    public static void insertStudent(int no,String name,String sex,int age,String dept){  
     com.ibatis.sqlmap.client.SqlMapClient client = null;  
     try{  
      client=new AppSqlConfig().getSqlMapInstance();  
   client.startTransaction();  
   Student student=new Student();  
   student.setSno(no);  
   student.setSname(name);  
   student.setSsex(sex);  
   student.setSage(age);  
   student.setSdept(dept);  
   client.insert("insertStudent",student);  
   client.commitTransaction();  
 }catch(SQLException e){  
     System.out.println(e.getMessage());  
 }finally {  
  try {  
   client.endTransaction();  
  } catch (SQLException e) {  
   e.printStackTrace();  
  }  
 }  
       
    }  
    //一个对象直接作为属性，实现关联  
    public static Student getStudent(){  
     com.ibatis.sqlmap.client.SqlMapClient client = null;  
  Student student=null;  
     try{  
          client=new AppSqlConfig().getSqlMapInstance();  
        client.startTransaction();  
       student = (Student)client.queryForObject("getStudent","xiaofeng");  
       client.commitTransaction();  
     }catch(SQLException e){  
         System.out.println(e.getMessage());  
     }finally{  
   try {  
    client.endTransaction();  
   } catch (SQLException e) {  
    e.printStackTrace();  
   }  
  }  
     return student;  
    }  
    //多个对象放到List中作为一个属性 实现关联，但是得嵌套查询。 测试一对多的关联查询  
    //也可以实现多对多  
    public static void reStudent(String name){  
     com.ibatis.sqlmap.client.SqlMapClient sqlMap = null;  
     sqlMap=new AppSqlConfig().getSqlMapInstance();  
     try{  
       sqlMap.startTransaction();  
       List studentList=sqlMap.queryForList("getStudent",name);  
         
       for(int i=0;i&lt;studentList.size();i++){  
        Student student=(Student)studentList.get(i);  
        System.out.println("姓名（表1）："+student.getSname());  
        for(int k=0;k&lt;student.getSc().size();k++){  
         SC sc=(SC)student.getSc().get(k);  
         Course course=(Course)sqlMap.queryForObject("getCourse", sc.getCno());  
         System.out.print("课程号（表2）："+sc.getCno());  
         System.out.print("------课程名（表3）："+course.getCname().trim()+"------分数（表2）: "+sc.getGrade()+"\\n");  
           
         }  
       }  
      
      sqlMap.commitTransaction();  
    }catch(SQLException e){  
        System.out.println(e.getMessage());  
    }finally{  
  try {  
   sqlMap.endTransaction();  
  } catch (SQLException e) {  
   e.printStackTrace();  
  }  
 }  
    }  
     
    public static void main(String args\[]){  
 //    update(2004131301,"xiaofeng","男",23,"信息");  
        reStudent("name2");  
        Student student=getStudent();  
     System.out.println("表4  描述："+student.getIntro().getIdescription());  
    
    // insertStudent(2004131305,"xiaofeng5","男",23,"信息"); ;  
      
    }  
     
}

//Course.java

package com.study.xiaofeng;  
import java.io.Serializable;  
public class Course implements Serializable{  
    private int cno;  
    private String cname;  
    private int ccredit;  
     
    public int getCno(){  
     return this.cno;  
    }  
    public void setCno(int no){  
     this.cno=no;  
    }  
    public String getCname(){  
     return this.cname;  
    }  
    public void setCname(String name){  
     this.cname=name;  
    }  
    public int getCcredit(){  
     return this.ccredit;  
    }  
    public void setCcredit(int credit){  
     this.ccredit=credit;  
    }  
}

//Intro.java

package com.study.xiaofeng;  
import java.io.Serializable;  
public class Intro implements Serializable{  
 private int sno;  
 private String idescription;  
   
 public int getSno(){  
  return this.sno;  
 }  
 public void setSno(int sno){  
  this.sno=sno;  
 }  
 public String getIdescription(){  
  return this.idescription;  
 }  
 public void setIdescription(String description){  
  this.idescription=description;  
 }  
}

//Sc.java

package com.study.xiaofeng;  
import java.io.Serializable;  
public class SC implements Serializable{  
    private int sno;  
    private int cno;  
    private int grade;  
    private Course course;  
     
    public int getSno(){  
     return this.sno;  
    }  
    public void setSno(int no){  
     this.sno=no;  
    }  
    public int getCno(){  
     return this.cno;  
    }  
    public void setCno(int no){  
     this.cno=no;  
    }  
    public int getGrade(){  
     return this.grade;  
    }  
    public void setGrade(int grade){  
     this.grade=grade;  
    }  
    public Course getCourse(){  
     return this.course;  
    }  
    public void setCourse(Course course){  
     this.course=course;  
    }  
}

//Student.java

package com.study.xiaofeng;  
import java.io.Serializable;  
import java.util.List;  
public class Student implements Serializable{  
    private int sno;  
    private String sname;  
    private String ssex;  
    private int sage;  
    private String sdept;  
    private List sc;  
    private Intro intro;  
    public int getSno(){  
     return this.sno;  
    }  
    public void setSno(int no){  
     this.sno=no;  
    }  
    public String getSname(){  
     return this.sname;  
    }  
    public void setSname(String name){  
     this.sname=name;  
    }  
    public String getSsex(){  
     return this.ssex;  
    }  
    public void setSsex(String sex){  
     this.ssex=sex;  
    }  
    public int getSage(){  
     return this.sage;  
    }  
    public void setSage(int age){  
     this.sage=age;  
    }  
    public String getSdept(){  
     return this.sdept;  
    }  
    public void setSdept(String dept){  
     this.sdept=dept;  
    }  
    public List getSc(){  
     return this.sc;  
    }  
    public void setSc(List sc){  
     this.sc=sc;  
    }  
    public Intro getIntro(){  
     return this.intro;  
    }  
    public void setIntro(Intro intro){  
     this.intro=intro;  
    }  
}

 

//运行结果如下：

![](http://p.blog.csdn.net/images/p_blog_csdn_net/ice_spar/0101.gif)