MyBatis 學(xué)習(xí)筆記(三)MyBatis與Spring 和SpringBoot整合

概述

接上一篇MyBatis 學(xué)習(xí)筆記(二)MyBatis常用特性運(yùn)用
在真實(shí)的項(xiàng)目我們幾乎不會(huì)將MyBatis 單獨(dú)運(yùn)用到項(xiàng)目中,而是將其整合到Spring框架或者SpringBoot中,本文將通過兩個(gè)demo演示MyBatis 與Spring和SpringBoot的整合。

在Spring中使用

在Spring中我們通過mybatis-spring 中間框架將MyBatis和Spring 兩個(gè)完全不相關(guān)的框架整合起來
該框架一方面負(fù)責(zé)加載和解析MyBatis相關(guān)配置,另一方面,該框架還會(huì)通過Spring提供的擴(kuò)展點(diǎn),把各種Dao接口對(duì)應(yīng)的對(duì)象放入IOC容器中。
本demo是一個(gè)maven項(xiàng)目,首先整合需要添加的依賴,如下

 <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.42</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

添加好依賴之后,我們需要在新建一個(gè)Spring的配置文件SpringContext.xml,該配置文件主要配置數(shù)據(jù)源,配置sqlSessionFactory用于生成SqlSession,配置MapperScannerConfigurer用于掃描接口,配置文件如下:

    <context:property-placeholder  location="jdbc.properties"/>

    <context:component-scan base-package="com.jay"/>
    <!--配置數(shù)據(jù)源-->
    <bean id="dataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource">
        <!-- 配置與數(shù)據(jù)庫交互的4個(gè)必要屬性 -->
        <property name="driver" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 給 SqlSessionFactory 配置數(shù)據(jù)源,這里引用上面的數(shù)據(jù)源配置 -->
        <property name="dataSource" ref="dataSource"/>
        <!--配置MyBatis-cfg.xml的路徑-->
        <property name="configLocation" value="MyBatis-cfg.xml"/>
        <!--配置映射文件-->
        <property name="mapperLocations" value="mybatis/*.xml"/>
    </bean>
    <!--配置MapperScannerConfigurer-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--配合Dao接口所在的包-->
        <property name="basePackage" value="com.jay.mapper"/>
    </bean>

接著我們還需要配置一下MyBatis的配置文件MyBatis-cfg.xml,配置如下:

<configuration>
     <settings>
         <setting name="cacheEnabled" value="true"/>
     </settings>

    <typeAliases>
        <typeAlias type="com.jay.entity.ClassRoom" alias="ClassRoom"/>
        <typeAlias type="com.jay.entity.Student" alias="Student"/>
    </typeAliases>
</configuration>

需要注意的是,MyBatis-cfg.xml 中的配置除了settings元素是必須配置在MyBatis 的配置文件中,其余元素都可以配置到Spring的配置文件中。
配置文件處理完成之后,接著我們來新建一個(gè)映射文件以及Dao 接口測(cè)試下
此處我新建了一個(gè)名為StudentMapper.xml的映射文件。

<mapper namespace="com.jay.mapper.StudentMapper">
    <resultMap id="studentResult" type="Student">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
        <result property="sexEnum" column="sex"
                typeHandler="com.jay.Handler.GeneralEnumHandler"/>
        <association property="classRoom" javaType="ClassRoom">
            <id property="id" column="id"/>
            <result property="name" column="name"/>
        </association>
    </resultMap>
    
    <resultMap id="classRoomResult" type="ClassRoom">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
    </resultMap>
    <select id="selectStudentById" resultMap="studentResult">
        SELECT s.id,s.`name`,s.age,s.sex,c.id,c.`name` FROM student s, class c
        WHERE s.class_id=c.id AND s.id=#{id}
    </select>

</mapper>

對(duì)應(yīng)的Dao接口如下:

@Repository
public interface StudentMapper {

    /**
     * 根據(jù)id查詢學(xué)生
     * @param id
     * @return
     */
    Student selectStudentById(Integer id);

}

最后我們新建一個(gè)測(cè)試類,測(cè)試下結(jié)果。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:SpringContext.xml")
public class StudentMapperTest {
    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void testSelectStudentById() {
        Student student = studentMapper.selectStudentById(1);
        System.out.println(student.toString());

    }
}

測(cè)試結(jié)果如下:
在這里插入圖片描述

小結(jié)

至此我們MyBatis與Spring的整合就完成了,當(dāng)然這是一個(gè)很小的示范demo,但是其包括了Spring與MyBatis整合的要點(diǎn)。其流程無非就是先引入相關(guān)的依賴,Spring的依賴和MyBatis的依賴等,接著就是對(duì)數(shù)據(jù)源,SqlSessionFactory等信息進(jìn)行配置,最后就是編寫映射文件和Dao接口。

源代碼

https://github.com/XWxiaowei/MyBatisLearn/tree/master/mybatis-spring-demo

在SpringBoot中使用

接下來我們學(xué)習(xí)下在SpringBoot 中整合MyBatis
首先我們需要新建一個(gè)SpringBoot項(xiàng)目,新建項(xiàng)目的細(xì)節(jié)再此處不詳細(xì)說明。新建完項(xiàng)目之后之后我們首先需要添加依賴

		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.0.1</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

然后在application.yml中添加相關(guān)的數(shù)據(jù)源,MyBatis的相關(guān)信息

#DataSource config 配置數(shù)據(jù)源信息
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatisdemo?useUnicode=true&characterEncoding=utf-8
    username: root
    password: admin
 #配置MyBatis的配置文件地址和MyBatis的映射文件地址  
mybatis:
  config-location: MyBatis-cfg.xml
  mapper-locations: mybatis/*.xml

接著我們還需要在啟動(dòng)類MybatisSpringbootDemoApplication中添加dao接口的掃描信息

@SpringBootApplication
@MapperScan(value = "com.jay.mapper")
public class MybatisSpringbootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(MybatisSpringbootDemoApplication.class, args);
	}

}

映射文件和Dao接口等同于上面所述的StudentMapper.xml 和StudentMapper,在此不再贅述。
最后我們看看測(cè)試類

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class StudentMapperTest {
    @Autowired
    private StudentMapper studentMapper;
    @Test
    public void selectStudentById() throws Exception {
        Student student = studentMapper.selectStudentById(1);
        System.out.println("---->查詢結(jié)果為={}"+student);
    }

}

測(cè)試結(jié)果如下:
在這里插入圖片描述

小結(jié)

本機(jī)我們通過一個(gè)demo闡述了SpringBoot與MyBatis的整合。我們可以很明顯的看出SpringBoot的配置相對(duì)較少,這與SpringBoot的理念相關(guān),約定大于配置,注解多于配置。

總結(jié)

本文通過兩個(gè)demo 闡述了MyBatis 與Spring和SpringBoot的整合過程。demo 比較簡(jiǎn)單,希望能對(duì)讀者有所幫助。

源代碼

https://github.com/XWxiaowei/MyBatisLearn/tree/master/mybatis-springboot-demo




作者:碼農(nóng)飛哥
微信公眾號(hào):碼農(nóng)飛哥