iBATIS实现的一个例子

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

工程目录结构如下:

//1、SQL MAP配置文件

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
    PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
    "http://www.ibatis.com/dtd/sql-map-config-2.dtd">

<sqlMapConfig> 
   <properties resource="com/study/xiaofeng/maps/SqlMapConfig.properties"/>
  <settings cacheModelsEnabled="true"
           enhancementEnabled="true"
        lazyLoadingEnabled="true"
        errorTracingEnabled="true"
        maxRequests="32"
        maxSessions="10"
        maxTransactions="5"
        useStatementNamespaces="false" />
 
 
 <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="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 sample" />
   <property name="Pool.PingEnabled" value="false" />
   <property name="Pool.PingConnectionsOlderThan" value="1" />
   <property name="Pool.PingConnectionsNotUsedFor" value="1" />
  </dataSource>
 </transactionManager>

<!--
<transactionManager type="JTA" >
<property name="UserTransaction"
value="java:comp/env/jdbc/framework"/>
<dataSource type="JNDI">
<property name="DataSource"
value="java:comp/env/jdbc/ibatistest"/>
</dataSource>
</transactionManager>


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

 

//2、SQL Map配置文件拥有唯一的<properties>元素,这样做后,在属性文件中定义的属性可以作为变量在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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="Student">

<typeAlias alias="student" type="com.study.xiaofeng.Student"/>
<typeAlias alias="course" type="com.study.xiaofeng.Course"/>
<typeAlias alias="intro" type="com.study.xiaofeng.Intro"/>
<typeAlias alias="sc" type="com.study.xiaofeng.SC"/>

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

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

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

 

 //4、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<studentList.size();i++){
        Student student=(Student)studentList.get(i);
        System.out.println("姓名(表1):"+student.getSname());
        for(int k=0;k<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;
    }
}

 

//运行结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一个用iBator生成iBatis有关代码的例子。 特别说明: Eclipse应该是3.4.1以上版本, 并且安装了iBator插件。否则可用iBator的命令行版本或ant工具。 测试用数据是: CREATE TABLE PERSON( id INTEGER NOT NULL, firstName VARCHAR (40) NOT NULL, lastName VARCHAR (40) NOT NULL, PRIMARY KEY (ID) ); insert into PERSON values (1,'ng','Huang'); insert into PERSON values (2,'zh','Ni'); insert into PERSON values (3,'zy','Huang'); src下有三个目录: ibator/config:配置文件,其中: ibatorConfig.xml:iBaotr的配置文件,指示iBator如何生成代码,其中classPathEntry要指向一个 jdbc 驱动程序。 sqlMapConfig.properties:数据库配置,配置数据库密码等 AppSqlConfig.java:应用程序配置,如果目录结构相同,不必修改 SqlMapConfig.xml:SqlMap配置,在最后应该加上每个表的Map文件,特别注意useStatementNamespaces="true"不能为false org:生成的代码,分为三个目录,目录名在ibatorConfig.xml中指定 注意:其中生成的person_SqlMap.xml中的: <select id="ibatorgenerated_selectByPrimaryKey" resultMap="ibatorgenerated_BaseResultMap" > 经过修改了, 删除了parameterClass="org....的内容 test:一个测试主程序。运行它能得到数据库中的数据。 如何使用这个例子: 1、下载后解压缩 2、导入到Eclipse中 3、运行test/Test.java,看看结果 4、删除org及其下的三个目录及文件 5、在ibator/config/ibatorConfig.xml中的右键菜单,选择Generate iBATIS Artifacts 5、将自动生成org中的所有代码,研究一下这些代码 6、修改中的person_SqlMap.xml中的: <select id="ibatorgenerated_selectByPrimaryKey" resultMap="ibatorgenerated_BaseResultMap" > 7、再次执行test/Test.java,看看结果 8、研究ibator/config中的各个文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值