spring与mybatis四种整合方法
一、采用org.mybatis.spring.mapper.MapperScannerConfigurer
整体结构如下图:
1、配置文件
1>applicationContext01.xml
- <?xmlversionxmlversion="1.0"encoding="UTF-8"?>
- <beansxmlns:xsibeansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"
- xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"
- xmlns:tx="http://www.springframework.org/schema/tx"xmlns:cache="http://www.springframework.org/schema/cache"
- xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx.xsd
- http://www.springframework.org/schema/cache
- http://www.springframework.org/schema/cache/spring-cache.xsd">
- <!-- 自动扫描 -->
- <context:component-scanbase-packagecontext:component-scanbase-package="com.hys.app.**.service,com.hys.app.**.dao,com.hys.app.**.action"/>
- <!-- 引入外置文件 -->
- <beanidbeanid="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <propertynamepropertyname="location"value="classpath:jdbc.properties"/>
- </bean>
- <!--数据库连接池配置-->
- <beanidbeanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">
- <propertynamepropertyname="driverClassName"value="${jdbc.driverClassName}"/>
- <propertynamepropertyname="url"value="${jdbc.url}"/>
- <propertynamepropertyname="username"value="${jdbc.username}"/>
- <propertynamepropertyname="password"value="${jdbc.password}"/>
- </bean>
- <!-- spring和MyBatis完美整合 -->
- <beanidbeanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
- <!-- 指定数据源 -->
- <propertynamepropertyname="dataSource"ref="dataSource"/>
- <!-- 具体指定xml文件,可不配 -->
- <propertynamepropertyname="configLocation" value="classpath:mybatis-config.xml"/>
- <!-- 自动扫描mapping.xml文件,**表示迭代查找 ,,也可在mybatis-config.xml中单独指定xml文件 -->
- <propertynamepropertyname="mapperLocations"value="classpath:com/hys/app/**/dao/*.xml"/>
- </bean>
- <!-- 自动扫描com/hys/app/**/dao下的所有dao接口,并实现这些接口,可直接在程序中使用dao接口,不用再获取sqlsession对象 -->
- <beanclassbeanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <!--
- basePackage 属性是映射器接口文件的包路径。
- 你可以使用分号或逗号 作为分隔符设置多于一个的包路径
- -->
- <propertynamepropertyname="basePackage"value="com/hys/app/**/dao"/>
- <!--
- 因为会自动装配 SqlSessionFactory和SqlSessionTemplate
- 所以没 有 必 要 去 指 定 SqlSessionFactory或 SqlSessionTemplate
- 因此可省略不配置;
- 但是,如果你使 用了一个 以上的 DataSource,那么自动装配可能会失效。
- 这种 情况下,你可以使用sqlSessionFactoryBeanName或sqlSessionTemplateBeanName属性来设置正确的 bean名称来使用;
- -->
- <propertynamepropertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"/>
- </bean>
- <!-- 事务管理器
- <bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <propertynamepropertyname="dataSource" ref="dataSource" />
- </bean>
- -->
- <!-- 使用声明式事务
- <tx:annotation-driventransaction-managertx:annotation-driventransaction-manager="txManager" />
- -->
- </beans>
2>jdbc.properties外置文件
- jdbc.driverClassName=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/demo?characterEncoding=UTF-8
- jdbc.username=root
- jdbc.password=root
3>mybatis-config.xml
- <?xmlversionxmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTDConfig 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
- <typeAliases>
- <typeAliastypetypeAliastype="com.hys.app.student.entity.Student"alias="Student"/>
- </typeAliases>
- </configuration>
4>studentMapper.xml
- <?xmlversionxmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPEmapperPUBLIC"-//mybatis.org//DTDMapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mappernamespacemappernamespace="com.hys.app.student.dao.StudentDao">
- <insertidinsertid="save"parameterType="Student">
- insert intot_app_student(id,name,sex,age) values(#{id},#{name},#{sex},#{age})
- </insert>
- <selectidselectid="getStudent"resultType="Student"parameterType="String">
- select * from t_app_student where id =#{id}
- </select>
- </mapper>
5>pom.xml
- <projectxmlnsprojectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>hys.web.project</groupId>
- <artifactId>hys_demo_ssm</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>hys_demo_ssm</name>
- <url>http://maven.apache.org</url>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- </properties>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.10</version>
- <scope>test</scope>
- </dependency>
- <!-- 数据源 -->
- <dependency>
- <groupId>commons-dbcp</groupId>
- <artifactId>commons-dbcp</artifactId>
- <version>1.4</version>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.0.8</version>
- </dependency>
- <!-- Mybatis3.4.1 -->
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis</artifactId>
- <version>3.4.1</version>
- </dependency>
- <!-- spring整合mybatis -->
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis-spring</artifactId>
- <version>1.3.0</version>
- </dependency>
- <!-- Spring-4.2.0 -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>4.2.0.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-orm</artifactId>
- <version>4.2.0.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-expression</artifactId>
- <version>4.2.0.RELEASE</version>
- </dependency>
- </dependencies>
- </project>
建立表:
- CREATE TABLE t_app_student
- ( id VARCHAR(32) NOT NULL PRIMARY KEY,
- name VARCHAR(15),
- sex VARCHAR(2),
- age INT
- )
2、创建action、service、dao、entity类
1>实体类Student
- packagecom.hys.app.student.entity;
- public class Student {
- private Stringid;
- private Stringname;
- private Stringsex;
- private int age;
- publicStudent(){
- }
- publicStudent(Stringid, Stringname, Stringsex,intage) {
- this.id =id;
- this.name =name;
- this.sex =sex;
- this.age =age;
- }
- public StringgetId() {
- returnid;
- }
- public void setId(String id) {
- this.id =id;
- }
- public StringgetName() {
- returnname;
- }
- public void setName(String name) {
- this.name =name;
- }
- public StringgetSex() {
- returnsex;
- }
- public void setSex(String sex) {
- this.sex =sex;
- }
- public int getAge() {
- returnage;
- }
- public void setAge(intage) {
- this.age =age;
- }
- @Override
- public StringtoString() {
- return"Student [id=" +id +", name=" +name +", sex=" +sex
- + ", age=" + age + "]";
- }
- }
2>dao接口
- packagecom.hys.app.student.dao;
- importcom.hys.app.student.entity.Student;
- public interface StudentDao {
- public void save(Student student);
- public Student getStudent(Stringid);
- }
3>service服务
- packagecom.hys.app.student.service;
- importorg.springframework.beans.factory.annotation.Autowired;
- importorg.springframework.stereotype.Service;
- importcom.hys.app.student.dao.StudentDao;
- importcom.hys.app.student.entity.Student;
- @Service
- publicclass StudentService {
- @Autowired
- private StudentDao studentDao;
- public void save(Student student) {
- studentDao.save(student);
- }
- public Student getStudent(String id) {
- Student student =studentDao.getStudent(id);
- return student;
- }
- }
4>action测试类
- packagecom.hys.app.student.action;
- importorg.junit.Test;
- importorg.springframework.beans.factory.annotation.Autowired;
- importorg.springframework.context.ApplicationContext;
- importorg.springframework.context.support.ClassPathXmlApplicationContext;
- importorg.springframework.stereotype.Controller;
- importcom.hys.app.student.entity.Student;
- importcom.hys.app.student.service.StudentService;
- @Controller
- publicclass StudentAction {
- @Autowired
- private StudentService studentService;
- @Test
- public void test1(){
- //获取上下文对象
- ApplicationContext context =newClassPathXmlApplicationContext("applicationContext01.xml");
- StudentAction studentAction =(StudentAction)context.getBean("studentAction");
- // Student student = newStudent("002","小明","男",20);
- // studentAction.studentService.save(student);
- Student std = studentAction.studentService.getStudent("001");
- System.out.println(std);
- }
- }
注:重复的文件在下面的例子中不在贴出来,在测试类中注意替换applicationContext01.xml文件名
二、采用数据映射器(MapperFactoryBean)的方式,不用写mybatis映射文件,采用注解方式提供相应的sql语句和输入参数
整体结构如下图:
1、配置文件
applicationContext04.xml
- <?xmlversionxmlversion="1.0"encoding="UTF-8"?>
- <beansxmlns:xsibeansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"
- xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"
- xmlns:tx="http://www.springframework.org/schema/tx"xmlns:cache="http://www.springframework.org/schema/cache"
- xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx.xsd
- http://www.springframework.org/schema/cache
- http://www.springframework.org/schema/cache/spring-cache.xsd">
- <!-- 自动扫描 -->
- <context:component-scanbase-packagecontext:component-scanbase-package="com.hys.app.**.service,com.hys.app.**.dao,com.hys.app.**.action"/>
- <!-- 引入外置文件 -->
- <beanidbeanid="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <propertynamepropertyname="location"value="classpath:jdbc.properties"/>
- </bean>
- <!--数据库连接池配置-->
- <beanidbeanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">
- <propertynamepropertyname="driverClassName"value="${jdbc.driverClassName}"/>
- <propertynamepropertyname="url"value="${jdbc.url}"/>
- <propertynamepropertyname="username"value="${jdbc.username}"/>
- <propertynamepropertyname="password"value="${jdbc.password}"/>
- </bean>
- <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
- <beanidbeanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
- <propertynamepropertyname="dataSource"ref="dataSource"/>
- </bean>
- <!--
- 创建数据映射器,数据映射器必须为接口
- 这种配置方式有个缺点,有多少个dao接口就要配置多少个数据映射器,增加了开发时间
- 可用MapperScannerConfigurer代替,能够完全解决问题
- <bean id="studentMapper"class="org.mybatis.spring.mapper.MapperFactoryBean">
- <propertynamepropertyname="mapperInterface"value="com.hys.app.student.dao.StudentDao" />
- <propertynamepropertyname="sqlSessionFactory"ref="sqlSessionFactory"/>
- </bean>
- -->
- <!-- 自动扫描com/hys/app/**/dao下的所有dao接口,并实现这些接口,可直接在程序中使用dao接口,不用再获取sqlsession对象 -->
- <beanclassbeanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <!--
- basePackage 属性是映射器接口文件的包路径。
- 你可以使用分号或逗号作为分隔符设置多于一个的包路径
- -->
- <propertynamepropertyname="basePackage"value="com/hys/app/**/dao"/>
- <!--
- 因为会自动装配 SqlSessionFactory和SqlSessionTemplate
- 所以没 有 必 要去 指 定 SqlSessionFactory或SqlSessionTemplate
- 因此可省略不配置;
- 但是,如果你使 用了一个 以上的 DataSource,那么自动装配可能会失效。
- 这种 情况下,你可以使用sqlSessionFactoryBeanName或sqlSessionTemplateBeanName属性来设置正确的 bean名称来使用;
- -->
- <propertynamepropertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"/>
- </bean>
- <!-- 事务管理器
- <bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource"/>
- </bean>
- -->
- <!-- 使用声明式事务
- <tx:annotation-driven transaction-manager="txManager" />
- -->
- </beans>
2、创建action、service、dao、entity类
1>dao接口
- packagecom.hys.app.student.dao;
- importorg.apache.ibatis.annotations.Insert;
- importorg.apache.ibatis.annotations.Select;
- importcom.hys.app.student.entity.Student;
- publicinterface StudentDao {
- @Insert(" insert intot_app_student(id,name,sex,age) values(#{id},#{name},#{sex},#{age})")
- public void save(Student student);
- @Select("select * from t_app_studentwhere id = #{id}")
- public Student getStudent(String id);
- }
2>service服务
- packagecom.hys.app.student.service;
- importorg.springframework.beans.factory.annotation.Autowired;
- importorg.springframework.stereotype.Service;
- importcom.hys.app.student.dao.StudentDao;
- importcom.hys.app.student.entity.Student;
- @Service
- publicclass StudentService {
- @Autowired
- private StudentDao studentDao;
- public void save(Student student) {
- studentDao.save(student);
- }
- public Student getStudent(String id) {
- Student student =studentDao.getStudent(id);
- return student;
- }
- }
三、采用抽象类org.mybatis.spring.support.SqlSessionDaoSupport提供SqlSession
整体结构如下图:
1、配置文件
applicationContext03.xml
- <?xmlversionxmlversion="1.0"encoding="UTF-8"?>
- <beansxmlns:xsibeansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"
- xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"
- xmlns:tx="http://www.springframework.org/schema/tx"xmlns:cache="http://www.springframework.org/schema/cache"
- xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx.xsd
- http://www.springframework.org/schema/cache
- http://www.springframework.org/schema/cache/spring-cache.xsd">
- <!-- 自动扫描 -->
- <context:component-scanbase-packagecontext:component-scanbase-package="com.hys.app.**.service,com.hys.app.**.dao,com.hys.app.**.action"/>
- <!-- 引入外置文件 -->
- <beanidbeanid="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <propertynamepropertyname="location"value="classpath:jdbc.properties"/>
- </bean>
- <!--数据库连接池配置-->
- <beanidbeanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">
- <propertynamepropertyname="driverClassName"value="${jdbc.driverClassName}"/>
- <propertynamepropertyname="url"value="${jdbc.url}"/>
- <propertynamepropertyname="username"value="${jdbc.username}"/>
- <propertynamepropertyname="password"value="${jdbc.password}"/>
- </bean>
- <beannamebeanname="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
- <propertynamepropertyname="dataSource"ref="dataSource"/>
- <propertynamepropertyname="mapperLocations"value="classpath:com/hys/app/**/dao/*.xml"/>
- </bean>
- <!-- 将sqlSessionTemplate手工注入到SqlSessionDaoSupport中 -->
- <beanidbeanid="sqlSessionTemplate"class="org.mybatis.spring.SqlSessionTemplate">
- <constructor-argindexconstructor-argindex="0"ref="sqlSessionFactory"/>
- </bean>
- </beans>
studentMapper.xml
- <?xmlversionxmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPEmapperPUBLIC"-//mybatis.org//DTDMapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mappernamespacemappernamespace="com.hys.app.student.dao.StudentDao">
- <insertidinsertid="save"parameterType="com.hys.app.student.entity.Student">
- insert intot_app_student(id,name,sex,age) values(#{id},#{name},#{sex},#{age})
- </insert>
- <selectidselectid="getStudent"resultType="com.hys.app.student.entity.Student"parameterType="String">
- select * from t_app_student where id =#{id}
- </select>
- </mapper>
2、创建action、service、dao、entity类
1>dao接口
- packagecom.hys.app.student.dao;
- importcom.hys.app.student.entity.Student;
- public interface StudentDao {
- public void save(Student student);
- public StudentgetStudent(Stringid);
- }
2>dao接口实现类
- packagecom.hys.app.student.dao;
- importjavax.annotation.Resource;
- importorg.mybatis.spring.SqlSessionTemplate;
- importorg.mybatis.spring.support.SqlSessionDaoSupport;
- importorg.springframework.stereotype.Service;
- importcom.hys.app.student.entity.Student;
- @Service
- publicclass StudentDaoImp extends SqlSessionDaoSupport implements StudentDao{
- /**
- * 我们发现这个类中没有把SqlSessionTemplate作为一个属性,因为我们继承了SqlSessionDaoSupport
- *SqlSessionDaoSupport他会提供sqlsession
- */
- @Override
- public void save(Student student) {
- // TODO Auto-generated method stub
- this.getSqlSession().insert("com.hys.app.student.dao.StudentDao.save",student);
- }
- @Override
- public Student getStudent(String id) {
- // TODO Auto-generated method stub
- returnthis.getSqlSession().selectOne("com.hys.app.student.dao.StudentDao.getStudent",id);
- }
- /**
- * 使用SqlSessionDaoSupport必须注意,此处源码1.1.1中有自动注入,1.2中取消了自动注入,需要手工注入,侵入性强
- * 也可在spring-mybatis.xml中如下配置,但是这种有多少个dao就要配置到多少个,多个dao就很麻烦。
- * <bean id="userDao"class="com.hua.saf.dao.UserDao">
- * <propertynamepropertyname="sqlSessionFactory" ref="sqlSessionFactory"/>
- * </bean>
- */
- @Resource
- public voidsetSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate){
- super.setSqlSessionTemplate(sqlSessionTemplate);
- }
- }
3>service服务
- packagecom.hys.app.student.service;
- importorg.springframework.beans.factory.annotation.Autowired;
- importorg.springframework.stereotype.Service;
- importcom.hys.app.student.dao.StudentDaoImp;
- importcom.hys.app.student.entity.Student;
- @Service
- publicclass StudentService {
- @Autowired
- private StudentDaoImp studentDaoImp;
- public void save(Student student) {
- studentDaoImp.save(student);
- }
- public Student getStudent(String id) {
- Student student =studentDaoImp.getStudent(id);
- return student;
- }
- }
四、采用接口org.apache.ibatis.session.SqlSession的实现类org.mybatis.spring.SqlSessionTemplate
整体结构如下图:
1、配置文件
applicationContext02.xml
- <?xmlversionxmlversion="1.0"encoding="UTF-8"?>
- <beansxmlns:xsibeansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"
- xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"
- xmlns:tx="http://www.springframework.org/schema/tx"xmlns:cache="http://www.springframework.org/schema/cache"
- xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx.xsd
- http://www.springframework.org/schema/cache
- http://www.springframework.org/schema/cache/spring-cache.xsd">
- <!-- 自动扫描 -->
- <context:component-scanbase-packagecontext:component-scanbase-package="com.hys.app.**.service,com.hys.app.**.dao,com.hys.app.**.action"/>
- <!-- 引入外置文件 -->
- <beanidbeanid="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <propertynamepropertyname="location"value="classpath:jdbc.properties"/>
- </bean>
- <!--数据库连接池配置-->
- <beanidbeanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">
- <propertynamepropertyname="driverClassName"value="${jdbc.driverClassName}"/>
- <propertynamepropertyname="url"value="${jdbc.url}"/>
- <propertynamepropertyname="username"value="${jdbc.username}"/>
- <propertynamepropertyname="password"value="${jdbc.password}"/>
- </bean>
- <beannamebeanname="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
- <propertynamepropertyname="dataSource"ref="dataSource"/>
- <propertynamepropertyname="mapperLocations"value="classpath:com/hys/app/**/dao/*.xml"/>
- </bean>
- <!--
- Mybatis-Spring为我们提供了一个实现了SqlSession接口的SqlSessionTemplate类,它是线程安全的,可以被多个Dao同时使用。
- 同时它还跟Spring的事务进行了关联,确保当前被使用的SqlSession是一个已经和Spring的事务进行绑定了的。
- 而且它还可以自己管理Session的提交和关闭。当使用了Spring的事务管理机制后,SqlSession还可以跟着Spring的事务一起提交和回滚。
- -->
- <beanidbeanid="sqlSessionTemplate"class="org.mybatis.spring.SqlSessionTemplate">
- <constructor-argindexconstructor-argindex="0"ref="sqlSessionFactory"/>
- </bean>
- </beans>
studentMapper.xml
- <?xmlversionxmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPEmapperPUBLIC"-//mybatis.org//DTDMapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mappernamespacemappernamespace="com.hys.app.student.dao.StudentDao">
- <insertidinsertid="save"parameterType="com.hys.app.student.entity.Student">
- insert intot_app_student(id,name,sex,age) values(#{id},#{name},#{sex},#{age})
- </insert>
- <selectidselectid="getStudent"resultType="com.hys.app.student.entity.Student"parameterType="String">
- select * from t_app_student where id =#{id}
- </select>
- </mapper>
2、创建action、service、dao、entity类
1>dao接口
- package com.hys.app.student.dao;
- import com.hys.app.student.entity.Student;
- public interface StudentDao {
- public void save(Student student);
- public Student getStudent(Stringid);
- }
2>service服务
- packagecom.hys.app.student.service;
- importorg.mybatis.spring.SqlSessionTemplate;
- importorg.springframework.beans.factory.annotation.Autowired;
- importorg.springframework.stereotype.Service;
- importcom.hys.app.student.entity.Student;
- @Service
- publicclass StudentService {
- /**
- *sqlSessionTemplate模板提供了sqlsession
- */
- @Autowired
- private SqlSessionTemplatesqlSessionTemplate;
- public void save(Student student) {
- sqlSessionTemplate.insert("com.hys.app.student.dao.StudentDao.save",student);
- }
- public Student getStudent(String id) {
- Student student =sqlSessionTemplate.selectOne("com.hys.app.student.dao.StudentDao.getStudent",id);
- return student;
- }
- }
1、采用MapperScannerConfigurer,它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean。
spring-mybatis.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.hua.saf" /> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}" /> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}" /> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件,**表示迭代查找 --> <property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" /> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 ,包下的类需要使用@MapperScan注解,否则容器注入会失败 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.hua.saf.*" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
UserMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- 为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的 例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀) --> <mapper namespace="com.hua.saf.dao.UserDao"> <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复, 使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型 resultType="com.hua.saf.User"就表示将查询结果封装成一个User类的对象返回,User类就是t_user表所对应的实体类 --> <!-- 根据id查询得到一个user对象--> <select id="getUser" parameterType="int" resultType="com.hua.saf.pojo.User"> select * from t_user where id=#{id} </select> </mapper>
dao类:
/** * 这里的@MapperScan就是上面所讲的Mapper扫描器中所需要的配置,会自动生成代理对象。 * 注意,接口中的方法名称要和对应的MyBatis映射文件中的语句的id值一样,因为生成的 * 动态代理,会根据这个匹配相应的Sql语句执行。另外就是方法的参数和返回值也需要注 * 意。接口中的方法如何定义,对应的MyBatis映射文件就应该进行相应的定义。 * 最后,标注中的userDao是用来作为Spring的Bean的id(或name)进行使用的,方便我 * 们在Service层进行注入使用。 */ @MapperScan public interface UserDao { //此处的方法名必须和mapper中的映射文件中的id同名 //回去映射文件中通过com.hua.saf.dao.UserDao.getUser,即this.getClass().getName()+".getUser" public User getUser(int id); }
service类:
@Service("userService") public class UserServiceImpl implements IUserService { @Resource private UserDao userDao; public User getUser(int id) { return userDao.getUser(id); } }
2、采用接口org.apache.ibatis.session.SqlSession的实现类org.mybatis.spring.SqlSessionTemplate。
mybatis中, sessionFactory可由SqlSessionFactoryBuilder.来创建。MyBatis-Spring 中,使用了SqlSessionFactoryBean来替代。SqlSessionFactoryBean有一个必须属性dataSource,另外其还有一个通用属性configLocation(用来指定mybatis的xml配置文件路径)。
spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.hua.saf" /> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}" /> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}" /> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:sqlMapConfig.xml"/> <!-- 自动扫描mapping.xml文件,**表示迭代查找,也可在sqlMapConfig.xml中单独指定xml文件--> <property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" /> </bean> <!-- mybatis spring sqlSessionTemplate,使用时直接让spring注入即可 --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <typeAlias type="com.hua.saf.pojo.User" alias="User" /> </typeAliases> </configuration>
User.java
public class User { private int id; private String username; private String password; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
UserDao.java
@Repository public class UserDao{ @Resource private SqlSessionTemplate sqlSessionTemplate; public User getUser(int id) { return sqlSessionTemplate.selectOne(this.getClass().getName() + ".getUser", 1); } }
UserService.java
@Service public class UserService{ @Resource private UserDao userDao; public User getUser(int id) { return userDao.getUser(id); } }
3、采用抽象类org.mybatis.spring.support.SqlSessionDaoSupport提供SqlSession。
spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.hua.saf" /> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}" /> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}" /> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:sqlMapConfig.xml"/> <!-- 自动扫描mapping.xml文件,**表示迭代查找,也可在sqlMapConfig.xml中单独指定xml文件--> <property name="mapperLocations" value="classpath:com/hua/saf/**/*.xml" /> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <typeAlias type="com.hua.saf.pojo.User" alias="User" /> </typeAliases> </configuration>
User.java
public class User { private int id; private String username; private String password; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
UserDao.java
@Repository public class UserDao extends SqlSessionDaoSupport{ public User getUser(int id) { return this.getSqlSession().selectOne(this.getClass().getName() + ".getUser", 1); } //使用SqlSessionDaoSupport必须注意,此处源码1.1.1中有自动注入,1.2中取消了自动注入,需要手工注入,侵入性强 //也可在spring-mybatis.xml中如下配置,但是这种有多少个dao就要配置到少个,多个dao就很麻烦。 //<bean id="userDao" class="com.hua.saf.dao.UserDao"> // <property name="sqlSessionFactory" ref="sqlSessionFactory"/> //</bean> @Resource public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { // TODO Auto-generated method stub super.setSqlSessionFactory(sqlSessionFactory); } }
UserService.java
@Service public class UserService{ @Resource private UserDao userDao; public User getUserss(int id) { return userDao.getUser(1); } }