Spring整合MyBatis总结

整合原理

  • MyBatis操作数据库,对数据库进行CRUD(增、删、改、查)操作时,实际原理是通过SqlSessionFactory对象---->产生SqlSession---->利用SqlSession产生的对象生成Mapper对象---->实现对数据库的CRUD操作。
  • 当利用Spring来整合MyBatis时,实际原理是将SqlSessionFactory对象交由Spring管理,从而实现两个框架的整合,达到操作数据库的目的。
  • 当使用spring整合mybatis时,数据库配置文件不再放入mybatis的conf.xml中,数据库的所有配置信息应放在spring的applicationContext.xml配置文件中。

需要使用的JAR包

  • mybatis-spring.jar-----spring整合mybatis使用
  • spring-tx.jar----spring对事务的支持
  • spring-jdbc.jar----spring访问数据库使用
  • spring-expression.jar-----spring表达式支持
  • spring-context-support.jar----spring应用上下文支持
  • spring-core.jar----spring核心代码支持
  • spring-context-----spring应用上线文
  • spring-beans.jar-----spring组件支持
  • spring-aop.jar-----spring对切面支持
  • spring-web.jar----spring对web项目支持
  • commons-logging.jar----日志支持
  • commons-dbcp.jar----数据源支持
  • ojdbc.jar----Oracle数据库驱动
  • mybatis.jar----mybatis核心支持
  • log4j.jar----日志支持
  • commons-pool.jar----数据库连接池

数据库相关配置信息

  • applicationContext.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 数据库配置信息,详细配置文件引入 -->
    <bean id="config" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
       <property name="locations">
          <array>
             <value>classpath:db.properties</value>
          </array>     
       </property>
    </bean>
    <!-- 配置数据库信息(调用db.properties配置文件中的配置信息) -->  
   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
       <property name="driverClassName" value="${driver}"></property>
       <property name="url" value="${url}"></property>
       <property name="username" value="${username}"></property>
       <property name="password" value="${password}"></property>
       <property name="maxIdle" value="${maxIdle}"></property>
       <property name="maxActive" value="${maxActive}"></property>
   </bean>
   <bean id="studentMapper" class="org.dsl.dao.impl.StudentDaoImpl">
     <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
   </bean>
   <bean id="studentService" class="org.dsl.service.impl.StudentServiceImpl">
      <property name="studentMapper" ref="studentMapper"></property>
   </bean>
   <!-- 在springIOC容器中创建Mybatis的核心类sqlSessionFactory -->
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <!-- 配置数据库信息 -->
     <property name="dataSource" ref="dataSource"></property> 
     <!-- 读取mybatis配置文件信息 -->
     <property name="configLocation" value="classpath:conf.xml"></property>  
   </bean>
</beans>


  • 其中dataSource中的信息可以直接配置到applicationContext.xml中,但是大多数采用配置文件db.properties的形式引入,方便维护管理。
  • db.properties配置信息:
driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:ORACLEDSL
username=scott
password=tiger
maxIdle=1000
maxActive=500
  • 其中配置dataSource时,需要使用commons-dbcp.jar中的org.apache.commons.dbcp.BasicDataSource类,这个类中包括了数据库driverClassName、URL、username、password、maxIdle和maxActive等等属性,根据具体需要进行配置即可。
  • 在加载配置文件db.properties时,需要使用org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer类所在父类PropertyPlaceholderConfigurer–父类PlaceholderConfigurerSupport–父类PropertyResourceConfigurer–父类PropertiesLoaderSupport中的private Resource[] locations属性,该属性是数组类型,可以配置多个。
  • 在springIOC容器中创建Mybatis的核心类sqlSessionFactory时需要用到mybatis-spring.jar中org.mybatis.spring.SqlSessionFactoryBean类,可以利用这个类中dataSource属性读取数据库配置信息,利用configLocation属性配置读取mybatis配置文件信息。

spring产生动态mapper对象的三种方法

  • 如上在springIOC容器中创建Mybatis的核心类sqlSessionFactory时,实现了spring利用mybatis中sqlSessionFactory对象操作数据库的权限,但是spring实现操作数据库的增删改查,必须要利用相应的数据库操作语句(sql语句),这时就需要spring产生mybatis最终操作需要的动态mapper对象,例如:StudentMapper对象,实际为StudentDao的接口类。
  • 第一种,通过DAO实现层继承SqlSessionDaoSupport类
    层级结构如下:
    在这里插入图片描述
    通过继承mybatis-spring.jar中的org.mybatis.spring.support.SqlSessionDaoSupport类,通过该类中提供的sqlSession对象来产生动态mapper对象。
package org.dsl.dao.impl;
import org.apache.ibatis.session.SqlSession;
import org.dsl.entity.Student;
import org.dsl.mapper.StudentMapper;
import org.mybatis.spring.support.SqlSessionDaoSupport;
public class StudentDaoImpl extends SqlSessionDaoSupport implements StudentMapper {

	@Override
	public void addStudent(Student student) {
		// TODO Auto-generated method stub
	   SqlSession session = super.getSqlSession();
	   //获取动态mapper对象
	   StudentMapper stuDao = (StudentMapper) session.getMapper(StudentMapper.class);
	   stuDao.addStudent(student);
	}

}

注:DAO的接口三层时的类名可以叫StudentDao,但是为了mapper接口和映射文件对应,所以建议将IStudentDao.java接口的名字改为StudentMapper与接口映射文件同名,接口映射文件的首字母小写。并且建议放在同一个类路径下,为了减少不必要配置。位置和文件如下:
在这里插入图片描述
1.Mapper 接口方法名和 Mapper.xml 中定义的每个 statement 的 id 同名。
2.Mapper 接口方法的输入参数类型和 rMapper.xml 中定义的 statement 的parameterType 类型相同。
3.Mapper 接口的返回类型和Mapper.xml 中定义的 statement 的 resultType 类型相同。

<?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" >
<!- namespace为接口全限定类名 -->
<mapper namespace = "org.dsl.mapper.StudentMapper">
<!-- id值为DAO中的方法名 -->
   <insert id="addStudent" parameterType="org.dsl.entity.Student">
     insert into student(stuNo,stuName,stuAge) values(#{stuNo},#{stuName},#{stuAge})   
   </insert>
</mapper>

加mybatis配置文件,改配置文件中放置载映射文件:
在这里插入图片描述

<?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>
  <mappers>
  <!-- 类位置用点(.)路径使用斜杠(/) -->
  <!-- 加载studentMapper.xml映射文件 -->
     <mapper resource="org/dsl/mapper/studentMapper.xml"/>
  </mappers>
</configuration>

最后将Dao层与sqlSessionFactory对象建立联系,将已经注入的sqlSessionFactory对象以属性的方式配置给Dao层。
在这里插入图片描述

配置完成调用测试

package org.dsl.test;

import org.dsl.entity.Student;
import org.dsl.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		StudentService studentService = (StudentService)context.getBean("studentService");
		Student student = new Student();
		student.setStuNo(2);
		student.setStuName("zds");
		student.setStuAge(20);
		studentService.addStudent(student);
	}

}

可省略提醒:src路径下面的mybatis配置文件conf.xml在spring整合mybatis时,是可以不用写的,因为在配置SqlSessionFactory时org.mybatis.spring.SqlSessionFactoryBean类中,有获取mapper映射文件的属性,mapperLocations该属性是数组,可以配置多个,可以使用通配符进行全包检索即可。当没有conf.xml文件时,就不能配置configLocation属性查找conf.xml文件,否则会报错。

   <!-- 配置sqlSessionFactory对象 -->
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <!-- 配置数据库信息 -->
     <property name="dataSource" ref="dataSource"></property> 
     <!-- 查找mapper映射文件 该属性为数组类型-->
     <property name="mapperLocations" value="org/dsl/mapper/*.xml"></property>  
   </bean>

在这里插入图片描述

主要步骤:在springIOC容器中配置数据库信息DataSource—>创建SqlSessionFactory对象(读取数据库信息、加载mybatis配置文件)—>将SqlSessionFactory对象与Dao层(StudentMapper)关联。

  • 第二种,利用mybatis-spring.jar中提供的org.mybatis.spring.mapper.MapperFactoryBean类实现动态mapper获取
    在第一种方法基础上删除StudentDaoImpl类和springIOC容器中的StudentDaoImpl的相关配置,利用mybatis-spring.jar中提供的org.mybatis.spring.mapper.MapperFactoryBean类中提供的属性指定mapper接口文件StudentMapper(即StudentDao的接口类)。
    在这里插入图片描述
    第二种方式缺点:如果存在多个类似于StudentMapper需要使用时,就要定义配置多个bean,代码较为冗余。

  • 第三种,利用mybatis-spring.jar中提供的Mapper扫描器(org.mybatis.spring.mapper.MapperScannerConfigurer),扫描指定的包路径下的所有mapper.xml配置文件。其中配置sqlSessionFactory对象的属性与前两种不同,需要使用sqlSessionFactoryBeanName属性才可以,并且需要指定要扫描的包,在利用相应的mapper属性时,在中ref需要配置mapper.java的文件名称首字母小写。
    在这里插入图片描述

  • 三种配置方法applicationContext.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 数据库配置信息,详细配置文件引入 -->
    <bean id="config" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
       <property name="locations">
          <array>
             <value>classpath:db.properties</value>
          </array>     
       </property>
    </bean>
    <!-- 配置数据库信息(调用db.properties配置文件中的配置信息) -->  
   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
       <property name="driverClassName" value="${driver}"></property>
       <property name="url" value="${url}"></property>
       <property name="username" value="${username}"></property>
       <property name="password" value="${password}"></property>
       <property name="maxIdle" value="${maxIdle}"></property>
       <property name="maxActive" value="${maxActive}"></property>
   </bean>
     <!-- 第一种配置 -->
   <bean id="studentMapper" class="org.dsl.dao.impl.StudentDaoImpl">
     <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
   </bean>
    <!-- 第二种配置 -->
    
    <bean id="studentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
      <property name="mapperInterface" value="org.dsl.mapper.StudentMapper"></property>
     <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
   </bean>
     <!-- 第三种配置 -->
    <!-- 批量产生多个mapper对象(批量产生多个mapper)
      产生的mapper在springIOC中使用时的ID值就是其接口文件的命名(接口名=id值) -->
   <bean id="mappers" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
      <property name="basePackage" value="org.dsl.mapper"></property>
     <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
   </bean>
   <bean id="studentService" class="org.dsl.service.impl.StudentServiceImpl">
      <property name="studentMapper" ref="studentMapper"></property>
   </bean>
   <!-- 配置sqlSessionFactory对象 -->
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <!-- 配置数据库信息 -->
     <property name="dataSource" ref="dataSource"></property> 
     <!-- 查找mapper映射文件 该属性为数组类型-->
     <property name="mapperLocations" value="org/dsl/mapper/*.xml"></property>  
   </bean>
</beans>

  • 整体流程
    在这里插入图片描述
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring整合MyBatis的原理可以总结为以下几步: 1. 配置数据源:在Spring配置文件中配置数据源,可以使用Spring自带的数据源或第三方数据源。 2. 配置SqlSessionFactory:SqlSessionFactory是MyBatis的核心配置对象,可以通过SpringMyBatis-Spring模块来配置SqlSessionFactory。 3. 配置MapperScannerConfigurer:MapperScannerConfigurer是MyBatis-Spring模块提供的一个扫描器,用于自动扫描Mapper接口并注册到Spring容器中。 4. 配置事务管理器:Spring提供了多种事务管理器,可以根据实际情况来选择。 总结一下,Spring整合MyBatis的过程就是将MyBatis的核心配置对象SqlSessionFactory和Mapper接口通过Spring的容器管理起来,并且使用Spring提供的事务管理器来管理事务。 具体的步骤如下: 1. 在Spring配置文件中配置数据源,可以使用Spring自带的数据源或第三方数据源。例如: ``` <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="123456" /> </bean> ``` 2. 配置SqlSessionFactory,可以使用MyBatis-Spring模块提供的SqlSessionFactoryBean来配置。例如: ``` <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.example.model" /> <property name="mapperLocations" value="classpath*:com/example/mapper/*.xml" /> </bean> ``` 其中,typeAliasesPackage用于指定实体类所在的包,mapperLocations用于指定Mapper XML文件所在的路径。 3. 配置MapperScannerConfigurer,可以使用MyBatis-Spring模块提供的MapperScannerConfigurer来配置。例如: ``` <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.example.mapper" /> </bean> ``` 其中,basePackage用于指定Mapper接口所在的包。 4. 配置事务管理器,可以使用Spring提供的事务管理器。例如: ``` <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> ``` 最后,在Service层的方法上添加@Transactional注解即可实现事务管理。 综上所述,Spring整合MyBatis的过程比较简单,只需要配置几个关键的对象即可。同时,Spring提供了很多方便的注解和工具类,可以更加方便地使用MyBatis

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值