IBatis与Spring的整合

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用系列 2核4GB
简介:
 由于想利用spring的强大的注入功能,又想利用ibatis对sql封装的轻巧功能,于是自己在想如何将他们整合起来。本人根据网上的实例,再做了一些分析,在本机做了实验。 本机环境:XP操作系统、2G内存、Ibatis2.3.4、spring2.0、mysql5.1、mysql-connect-java-5.0.4-bin.jar。
 

1、Mysql准备数据(use itcast数据库)

mysql>  create  table student(id  int  primary  key auto_increment, firstname  varchar
(20), lastname  varchar(20));

2、准备POJO类

package cn.itcast;

public  class Student  implements java.io.Serializable {
   private  static  final  long serialVersionUID = 1L;
   private Integer id;
   private String firstname;
   private String lastname;

   public String getFirstname() {
     return firstname;
  }

   public  void setFirstname(String firstname) {
     this.firstname = firstname;
  }

   public Integer getId() {
     return id;
  }

   public  void setId(Integer id) {
     this.id = id;
  }

   public String getLastname() {
     return lastname;
  }

   public  void setLastname(String lastname) {
     this.lastname = lastname;
  }
}

3、准备3大类配置文件, 都在包configfile下面

(1)与POJO的映射文件:Student.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">
  <!-- 这是POJO映射文件的根元素-->
< sqlMap  namespace ="Student" >
  <!--
    select元素的id属性用来标识此元素,resultClass属性的值是Java类的全限定名(即包括类的包名)。
    resultClass属性可以让您指定一个Java类,根据ResultSetMetaData将其自动映射到JDBC的ResultSet。
    只要是Java Bean的属性名称和ResultSet的列名匹配,属性自动赋值给列值。
    parameterClass属性是参数的类型,此属性的值是Java类的全限定名(即包括类的包名)。 它是可选的,但强烈建议使用。它的目的是
    限制输入参数的类型为指定的Java类,并 优化框架的性能。
  
-->
   < select  id ="getStudentById"  resultClass ="cn.itcast.Student"
     parameterClass ="int" >
    select id,firstname,lastname from student where id=#value#
   </ select >

   < insert  id ="insertStudent"  parameterClass ="cn.itcast.Student" >
    insert into student(firstname,lastname) values(#firstname#,#lastname#)
   </ insert >
</ sqlMap >
(2)连接mysql数据库的配置文件:jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/itcast
jdbc.username=root
jdbc.password=admin
 
(3)Ibatis的总控文件:sql-map-config.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 >
   < sqlMap  resource ="configfile/Student.xml"  />
</ sqlMapConfig >
3、此时该Spring出场了,Spring的配置文件(applicationContext.xml)将jdbc.properties配置文件的内容关联成DataSource,再把DataSource关联到Ibatis的配置文件, 最后统一封装成为SqlMapClientTemplate模板类向外提供服务。 
<? xml  version ="1.0"  encoding ="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

< beans >
  <!-- 此bean告诉Spring去哪找数据库的配置信息,因为有此Bean才出现下面用${}标记来取变量的语句-->
   < bean  id ="propertyConfig"
     class ="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
     < property  name ="location" >
       < value >configfile/jdbc.properties </ value >
     </ property >
   </ bean >

  <!-- 配置一个数据源,根据上面propertyConfig指定的location去找数据库连接的配置信息-->
   < bean  id ="dataSource"
     class ="org.springframework.jdbc.datasource.DriverManagerDataSource" >
     < property  name ="driverClassName" >
       < value >${jdbc.driver} </ value >
     </ property >
     < property  name ="url" >
       < value >${jdbc.url} </ value >
     </ property >
     < property  name ="username" >
       < value >${jdbc.username} </ value >
     </ property >
     < property  name ="password" >
       < value >${jdbc.password} </ value >
     </ property >
   </ bean >

  <!-- 根据dataSource和configLocation创建一个SqlMapClient-->
   < bean  id ="sqlMapClient"  class ="org.springframework.orm.ibatis.SqlMapClientFactoryBean" >
     < property  name ="configLocation" >
       < value >configfile/sql-map-config.xml </ value >
     </ property >
     < property  name ="dataSource" >
       < ref  bean ="dataSource"  />
     </ property >
   </ bean >

  <!-- 根据sqlMapClien创建一个SqlMapClient模版类-->
   < bean  id ="sqlMapClientTemplate"  class ="org.springframework.orm.ibatis.SqlMapClientTemplate" >
     < property  name ="sqlMapClient" >
       < ref  bean ="sqlMapClient"  />
     </ property >
   </ bean >

  <!-- 将上面的模版类织入到我们的DAO对象中-->
   < bean  id ="studentDao"  class ="cn.itcast.StudentDaoSqlMap" >
     < property  name ="sqlMapClientTemplate" >
       < ref  bean ="sqlMapClientTemplate"  />
     </ property >
   </ bean >

</ beans >
 

4、在Dao层使用模板类

此时再次可以Spring的强大的注入功能,将SqlMapClientTemplate注入到DAO层之中,这样就可以像操作对象一样操作数据库了。
package cn.itcast;

import org.springframework.orm.ibatis.SqlMapClientTemplate;

public  class StudentDaoSqlMap {
   private SqlMapClientTemplate sqlMapClientTemplate;

   public SqlMapClientTemplate getSqlMapClientTemplate() {
     return sqlMapClientTemplate;
  }

   public  void setSqlMapClientTemplate(
      SqlMapClientTemplate sqlMapClientTemplate) {
     this.sqlMapClientTemplate = sqlMapClientTemplate;
  }

   // 此方法的返回值与Student.xml的select元素的resultClass对应.
   public Student getStudent(Integer id) {
     return (Student) sqlMapClientTemplate.queryForObject( "getStudentById",
        id);
     // 注意:queryForObject方法返回一个Object,第一个参数与Student.xml的select元素
     // 的id属性值对应,第二个参数的类型与Student.xml的select元素的parameterClass
     // 属性值对应.
  }

   public Object insertStudent(Student student) {
     return sqlMapClientTemplate.insert( "insertStudent", student);
  }
}

5、客户端测试:Client.java

package cn.itcast;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public  class Client {

   public  static  void main(String[] args) {
    ApplicationContext factory =  new ClassPathXmlApplicationContext(
         "applicationContext.xml");

    StudentDaoSqlMap studentDao = (StudentDaoSqlMap) factory
        .getBean( "studentDao");

     // 插入一个student
    Student student =  new Student();
    student.setFirstname( "tian");
    student.setLastname( "xiangdong");
    studentDao.insertStudent(student);

     // 查询出id是1的Student对象.
     // Student student = studentDao.getStudent(1);
     // System.out.println(student.getId());
     // System.out.println(student.getFirstname());
     // System.out.println(student.getLastname());
  }

}

6、总结

【注意】 其中用到了Spring读取properites文件的PropertyPlaceholderConfigurer类,配置称DataSource的DriverManagerDataSource类,对Ibatis配置文件的工厂类SqlMapClientFactoryBean, 统一向外提供服务的SqlMapClientTemplate模板类等, 最后把这个摸版类再注入到需要的Dao层之中。 一定到理顺他们之间的关系,这个很关键。


本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/275723,如需转载请自行联系原作者
相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
Java SSH/SSI框架科普(Struts+Spring+Hibernate/Ibatis)
Java SSH/SSI框架科普(Struts+Spring+Hibernate/Ibatis)
341 0
|
Java 关系型数据库 数据库连接
|
XML Java 数据格式
xml中${}的使用含义(美元符号大括号,以Spring、ibatis、mybatis为例)
xml中${}的使用含义(美元符号大括号,以Spring、ibatis、mybatis为例)  转: 项目中,经常会在xml中看到这样的写法: 看到了${}这样的表达式,脑海里面第一印象是不是我们jsp中的EL表达式?! 哈哈。
3796 0