02-整合spring和mybatis

配置spring和mybatis整合

spring-persist-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:context="http://www.springframework.org/schema/context"
       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">
    <!-- 加载外部数据库连接信息文件 -->
    <context:property-placeholder location="jdbc.properties"/>
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定mybatis全局配置文件的位置 -->
        <property name="configLocation" value="mybatis-config.xml"/>
        <!-- 指定mapper.xml配置文件的位置 -->
        <property name="mapperLocations" value="mapper/*Mapper.xml"/>
        <!-- 装配数据源dataSource -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="top.bigking.crowd.mapper"/>
    </bean>

</beans>

注意:druid连接池中的参数name必须规范,不能随便设置。

spring整合mybatis的配置可能比较难记

所以应该按照逻辑捋顺一遍,可能会帮助记忆。

首先,我们创建好项目后,应该书写Mapper接口,Mapper.xml文件

为了让mybatis的一些设置生效,我们会习惯性书写一个mybatis-config.xml

在我们单独使用mybatis时,会把数据库连接的某些设置写在mybatis-config.xml中

而现在我们同时使用spring和mybatis,所以在spring-persist-mybatis.xml中写一个dataSource的bean对象

接下来,就是重点,由于Spring使用mybatis都是通过SqlSessionFactory这一个bean对象来完成的

所以我们需要写一个SqlSessionFactory这个bean对象

那么,首先我们为了使用mybatis,引入mybatis-config.xml就很明显了吧。(需要记住configLocation)

接下来就是写有SQL的Mapper.xml文件。(记住 MapperLocations)

然后装配dataSource数据源,这就不必赘述。

最后我们还没有引入Mapper接口,因为是interface,不是xml文件,我们一般通过bean对象的方式引入。(org.mybatis.spring.mapper.MapperScannerConfigurer,参数是basePackage)

金麟岂是池中物,一遇风云便化龙!
原文地址:https://www.cnblogs.com/ABKing/p/12492091.html