温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用MyBatis怎么对Spring进行无缝对接

发布时间:2020-12-03 16:04:02 来源:亿速云 阅读:125 作者:Leah 栏目:编程语言

本篇文章给大家分享的是有关使用MyBatis怎么对Spring进行无缝对接,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

1.为什么会出现MyBatis-Spring

Spring框架与MyBatis框架是Java互联网技术的主流框架。但是如何将MyBatis无缝整合到Spring框架中呢?这时候就诞生了MyBatis-Spring。使用这个类库中得类,Spring将会加载必要的MyBatis工厂类和session类。

Spring3.0也仅仅支持ibatis2.0。本来将MyBatis3的支持添加到Spring3.0中。而不幸,Spring3.0的开发在MyBatis3.0官方发布前就结束了。因为Spring开发团队不想发布一个非发布版的MyBatis的整合支持。就放弃了对MyBatis的支持。

随着Spring越来越成为java事实标准的技术框架。Spring 4.0 移除了对iBatis的直接支持。MyBatis团队开发出来了基于Spring的MyBatis整合Jar---MyBatis-Spring。

2.使用MyBatis-Spring的好处

1.使得业务层和模型层得到更好的分离。再Spring框架中MyBatis也更加简单,节约不少的代码

2.甚至不需要显示的使用SqlSessionFactory、SqlSessiond等对象

3.MyBatis-Spring组成部分

1.配置数据源

2.配置SqlSessionFactory

3.配置SqlSessionTemplate

4.配置Mapper

5.事务处理

MyBatis中要构建SqlSessionFactory对象,让它产生SqlSession,而在MyBatis-Spring项目中SqlSession的使用是通过SqlSessionTemplate来实现的,它提供了对SqlSession操作的封装。所以可以通过SqlSessionTemplate可以得到Mapper。

4.在Spring MVC中配置

4.1 配置SqlSessionFactoryBean

在基本的 MyBatis中,session工厂可以使用SqlSessionFactoryBuilder 来创建。而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean 来替代。

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 <property name="dataSource" ref="dataSource" />
</bean>

注意点

SqlSessionFactory 有一个单独的必须属性,就是 JDBC 的 DataSource

在SqlSessionFactoryBean的返回getObject的时候,有个验证。

@Override
 public SqlSessionFactory getObject() throws Exception {
  if (this.sqlSessionFactory == null) {
   afterPropertiesSet();
  }

  return this.sqlSessionFactory;
 }
 @Override
 public void afterPropertiesSet() throws Exception {
  notNull(dataSource, "Property 'dataSource' is required");
  notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
  state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),
       "Property 'configuration' and 'configLocation' can not specified with together");
  this.sqlSessionFactory = buildSqlSessionFactory();
 }

4.2配置datasource

这里我们使用的是阿里巴巴的数据库连接池。https://github.com/alibaba/druid

compile group: 'com.alibaba', name: 'druid', version: '1.1.2'
<!--阿里巴巴的数据库连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
  <!-- 基本属性 url、user、password -->
  <property name="url" value="${jdbc_url}"/>
  <property name="username" value="${jdbc_user}"/>
  <property name="password" value="${jdbc_password}"/>
</bean>

4.3配置数据库链接属性

在resource目录下创建properties文件夹,并创建datasource.properties

jdbc_url=jdbc:mysql://localhost:3306/cnblogs&#63;serverTimezone=Asia/Shanghai&characterEncoding=utf8
jdbc_user=root
jdbc_password=root

使用阿里巴巴的数据库连接池是无需配置数据库驱动。是根据url的前缀来判断的

4.4配置Spring加载配置属性及配置替换动态标签

<!--加载配置文件路径-->
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="location" value="classpath:properties/datasource.properties"></property>
</bean>
<!--获取配置属性之后动态替换标签-->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
  <property name="properties" ref="configProperties"/>
</bean>

4.5配置Spring自动创建Mapper接口的bean

MyBatis-Spring提供了一个转换器MapperScannerConfigurer,可以将映射接口转换为Spring容器中Bean。这样就可以在代码中注入映射的bean

<!--采用自动扫描方式创建Mapper Bean-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.cnblogs.dao"></property>
</bean>

basePackage属性是让你为映射器接口文件设置基本的包路径。 你可以使用分号或逗号作为分隔符设置多于一个的包路径。每个映射器将会在指定的包路径中递归地被搜索到。

4.6配置事务

MyBatis和Spring结合后是使用Spring AOP去管理事务的,使用Spring AOP是相当的简单的,它分为声明式事务和编程性事务。大部分场景下使用声明式事务就可以了。

引入Jar包

compile group: 'org.springframework', name: 'spring-tx', version: '4.3.10.RELEASE'
compile group: 'org.springframework', name: 'spring-jdbc', version: '4.3.10.RELEASE'
<!--事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource" />
</bean>
<!--使用声明式事务管理方式-->
<tx:annotation-driven transaction-manager="transactionManager"/>

5.完整的Spring xml配置及引用的Jar包

引入的Jar列表

compile group: 'org.springframework', name: 'spring-webmvc', version: '4.3.10.RELEASE'
compile group: 'org.springframework', name: 'spring-tx', version: '4.3.10.RELEASE'
compile group: 'org.springframework', name: 'spring-jdbc', version: '4.3.10.RELEASE'
compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
compile group: 'org.mybatis', name: 'mybatis-spring', version: '1.3.1'
compile group: 'org.mybatis', name: 'mybatis', version: '3.4.5'
compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
compile group: 'com.alibaba', name: 'druid', version: '1.1.2'

Spring的配置

<&#63;xml version="1.0" encoding="UTF-8"&#63;>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
  <!--spring可以自动去扫描base-pack下面的包或者子包下面的Java文件-->
  <context:component-scan base-package="com.cnblogs.controller,com.cnblogs.service,com.cnblogs.dao"/>
  <!--自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdpter-->
  <mvc:annotation-driven/>
  <!-- 对静态资源文件的访问-->
  <mvc:default-servlet-handler/>
  <!--加载配置文件路径-->
  <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="location" value="classpath:properties/datasource.properties"></property>
  </bean>
  <!--获取配置属性之后动态替换标签-->
  <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
    <property name="properties" ref="configProperties"/>
  </bean>
  <!--阿里巴巴的数据库连接池-->
  <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
    <!-- 基本属性 url、user、password -->
    <property name="url" value="${jdbc_url}"/>
    <property name="username" value="${jdbc_user}"/>
    <property name="password" value="${jdbc_password}"/>
  </bean>
  <!--构建SqlSessionFactory-->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:config/mybatis-config.xml"/>
    <property name="mapperLocations" value="classpath:mappers/*.xml"/>
  </bean>
  <!--采用自动扫描方式创建Mapper Bean-->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.cnblogs.dao"></property>
  </bean>
  <!--事务管理器-->
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
  </bean>
  <!--使用声明式事务管理方式-->
  <tx:annotation-driven transaction-manager="transactionManager"/>
  <!--视图解析器-->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/content"></property>
    <property name="suffix" value=".jsp"></property>
  </bean>
</beans>

以上就是使用MyBatis怎么对Spring进行无缝对接,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI