您的位置:首页 > 编程语言 > Java开发

MyBatis与Spring集成示例

2014-03-21 09:44 232 查看
本示例将使用MyBatis与Spring集成的方式改写上篇博文的工程。为此,应将工程用到的相关jar包复制到工程的lib目录中。读者可在本文下方的“附件下载”处下载本示例的工程,因此在这里就不详述要用到的jar包了(受单个附件最大尺寸限制,不能把工程打包为一个文件。第一个附件是工程,后两个附件是不能一起打包的jar包。读者下载后把后两个附件中的jar包解压缩后复制到工程的lib目录下即可)。

一、集成所需要的粘合剂

      就是mybatis-spring包。这是MyBatis官方提供的用来与Spring集成的jar包,它是集成的核心部分,本示例使用的是mybatis-spring-1.1.1.jar。

二、Spring的配置

      本示例使用Spring 3.1.2。

      配置文件(beans.xml)的内容如下:

<?xmlversion="1.0"encoding="utf8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="  

            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  

            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  

            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  

            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd  

            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"  

default-autowire="byName"default-lazy-init="false">

  <!--本示例采用DBCP连接池,应预先把DBCP的jar包复制到工程的lib目录下。  

  连接池配置如下-->

<beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource">

<propertyname="driverClassName"value="com.mysql.jdbc.Driver"/>

<propertyname="url"

value="jdbc:mysql://localhost/courseman"/>

<propertyname="username"value="courseman"/>

<propertyname="password"value="abc123"/>

</bean>

<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">

<!--dataSource属性指定要用到的连接池-->

<propertyname="dataSource"ref="dataSource"/>

<!--configLocation属性指定mybatis的核心配置文件-->

<propertyname="configLocation"value="resources/configuration.xml"/>

</bean>

<beanid="studentMapper"class="org.mybatis.spring.mapper.MapperFactoryBean">

<!--sqlSessionFactory属性指定要用到的SqlSessionFactory实例-->

<propertyname="sqlSessionFactory"ref="sqlSessionFactory"/>

<!--mapperInterface属性指定映射器接口,用于实现此接口并生成映射器对象-->

<propertyname="mapperInterface"value="com.abc.mapper.StudentMapper"/>

</bean>

</beans>

      需要注意的是,以上sqlSessionFactory的配置有其特殊之处。它的class是org.mybatis.spring.SqlSessionFactoryBean,此类实现了Srping中的一个接口org.springframework.beans.factory.FactoryBean,这个接口声明了一个方法getObject()。这意味着,当我们要引用sqlSessionFactory这个bean的时候,返回的不是类SqlSessionFactoryBean的实例,而是此实例的getObject()方法的返回值。而SqlSessionFactoryBean对此方法的实现,是返回了一个SqlSessionFactory对象。也就是说,SqlSessionFactoryBean的实例是用来生成SqlSessionFactory对象的工厂。

      紧接着的studentMapper的配置与此原理一致。

      将此文件与MyBatis的配置文件放在一起,即工程的src\resources目录下。此目录会被ant复制到classes目录中,而classes目录会被ant添加到类加载路径中。

三、MyBatis的配置

      由于已在Spring中配置好了数据源,因此MyBatis的核心配置文件configuration.xml中的environments元素可不再需要。其它元素与以前一致。而映射文件StudentMapper.xml则无须任何改动。

四、执行类

      执行类(MyBatisSpringDemo.java)代码如下。

package com.demo;  

import org.springframework.context.ApplicationContext;  

import com.abc.mapper.StudentMapper;  

import com.abc.domain.Student;  

import org.springframework.context.support.ClassPathXmlApplicationContext;  

publicclass MyBatisSpringDemo  

{  

privatestatic ApplicationContext ctx;  

static

    {  

//在类路径下寻找resources/beans.xml文件 

        ctx = new ClassPathXmlApplicationContext("resources/beans.xml");  

    }  

publicstaticvoid main(String[] args)  

    {  

        StudentMapper mapper =   

               (StudentMapper)ctx.getBean("studentMapper");  

//笔者的数据库中只有ID为4的学生。读者若运行此程序, 

//须使用你的数据库中存在的学生ID。否则报空指针异常 

        Student student = mapper.getById(4);  

//使用StringBuilder的append操作代替字符串的“+” 

//操作可提高执行效率 

        StringBuilder sb = new StringBuilder("学生信息:\n");  

        sb.append("姓名:");  

        sb.append(student.getName());  

        sb.append(" ");  

        sb.append( "专业:");  

        sb.append(student.getMajor());  

        sb.append(" 年级:");  

        sb.append(student.getGrade());  

        sb.append("\n");  

        sb.append("指导教师信息:\n");  

        sb.append("姓名:");  

        sb.append(student.getSupervisor().getName());  

        sb.append(" ");  

        sb.append("职称:");  

        sb.append(student.getSupervisor().getTitle());  

        sb.append(" ");  

        sb.append("研究方向:");  

        sb.append(student.getSupervisor().getResearchArea());  

        System.out.println(sb.toString());  

    }  



      修改ant的build.xml文件,指定此类为执行类。

<!--指定MyBatisSpringDemo为要运行的类-->

<javafork="true"classname="com.demo.MyBatisSpringDemo"

classpathref="library">

      执行结果如下:




五、可能会遇到的错误

      1、jar包版本不匹配

      笔者本来使用的MyBatis包是mybatis-3.0.6.jar,然而却报出NoSuchMethodError,也就是找不到org.apache.ibatis.session.configuration的setDatabaseId方法。如下图所示:




      由上图可看出,应该是mybatis-spring组件调用了此方法,而这个方法mybatis-3.0.6.jar没有提供,因此报错。换为mybatis-3.1.1.jar即可。

      2、字符集问题

      若工程中配置文件的编码(即encoding属性)是UTF-8,再往这些文件添加中文注释,则会报出类似“Invalid byte 1 of 1-byte UTF-8 sequence”的错误。如下图所示:




      把编码改为utf8或gbk即可解决此问题。

【MyBatis学习笔记】系列之预备篇一:ant的下载与安装

【MyBatis学习笔记】系列之预备篇二:ant入门示例

【MyBatis学习笔记】系列之一:MyBatis入门示例

【MyBatis学习笔记】系列之二:MyBatis增删改示例

【MyBatis学习笔记】系列之三:MyBatis的association示例

【MyBatis学习笔记】系列之四:MyBatis association的两种形式

【MyBatis学习笔记】系列之五:MyBatis与Spring集成示例

【MyBatis学习笔记】系列之六:MyBatis与Spring集成示例续

【MyBatis学习笔记】系列之七:MyBatis一对多双向关联

【MyBatis学习笔记】系列之八:MyBatis MapperScannerConfigurer配置

【MyBatis学习笔记】系列之九:MyBatis collection的两种形式

【MyBatis学习笔记】系列之十:MyBatis日志之Log4j示例

【MyBatis学习笔记】系列之十一:MyBatis多参数传递之注解方式示例

【MyBatis学习笔记】系列之十二:MyBatis多参数传递之默认命名方式示例

【MyBatis学习笔记】系列之十三:MyBatis多参数传递之Map方式示例

【MyBatis学习笔记】系列之十四:MyBatis中的N+1问题

【MyBatis学习笔记】系列之十五:MyBatis多参数传递之混合方式

【MyBatis学习笔记】系列之十六:Spring声明式事务管理示例

【MyBatis学习笔记】系列之十七:MyBatis多对多保存示例

本文出自 “肖凡的专栏” 博客,请务必保留此出处http://legend2011.blog.51cto.com/3018495/946579
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mybatis