1. 程式人生 > 其它 >Spring的藝術(六):一文搞定Spring整合Mybatis

Spring的藝術(六):一文搞定Spring整合Mybatis

技術標籤:《框架的藝術》系列mybatisspringjavamysql

聽說微信搜尋《Java魚仔》會變更強哦!

本文收錄於JavaStarter ,裡面有我完整的Java系列文章,學習或面試都可以看看哦

(一)概述

有個專門的專案可以用來整合Spring和Mybatis,這裡還是先放上官網:

http://mybatis.org/spring/zh/index.html

MyBatis-Spring 會幫助你將 MyBatis 程式碼無縫地整合到 Spring 中,首先需要確定版本:

在這裡插入圖片描述
在這裡會用最新的版本去做這個整合。

(二)Spring整合Mybatis操作

2.1 引入依賴

在這裡我會用spring-jdbc代替mybatis的資料來源,因此額外引入了一個spring-jdbc的依賴,其餘就是Spring相關依賴和Mybatis相關依賴以及最重要的mybatis-spring

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.4</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <
version
>
5.1.46</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency> <dependency> <groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId> <version>5.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency>

2.2 專案準備

我這裡只搭建一個最簡單的專案框架,包含一個使用者的實體類,以及一個UserMapper介面和UserMapper.xml檔案:

public class User {
    private int id;
    private String name;
    //省略構造方法、get、set、toString
}

UserMapper

public interface UserMapper {
    List<User> getUserList();
}

UserMapper.xml

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.javayz.mapper.UserMapper">
    <select id="getUserList" resultType="com.javayz.pojo.User">
        select * from user;
    </select>
</mapper>

2.3 配置mybatis-config.xml

由於Spring和Mybatis整合後,mybatis-config甚至可以被spring的配置檔案所代替,但是為了演示,我依舊會建立這個配置檔案:

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--每個mapper.xml都需要在mybatis配置檔案中進行配置-->
    <mappers>
        <mapper resource="com/javayz/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

2.4 配置Spring-mybatis配置檔案

這個檔案是spring-mybatis的核心配置檔案spring.xml

<?xml version="1.0" encoding="UTF8"?>
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

        <!--DataSource由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/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </bean>

        <!--配置SqlSessionFactory-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="datasource"/>
            <!--繫結Mybatis配置檔案-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
        <!--配置sqlSessionTemplate-->
        <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>

</beans>

這個配置檔案中主要會配置三個東西:DataSource資料來源、SqlSessionFactory、SqlSessionTemplate

DataSource資料來源就不用多講了,和Mybatis一樣。

在 MyBatis-Spring 中,可使用 SqlSessionFactoryBean來建立 SqlSessionFactory,並給他配置資料來源、繫結Mybatis配置檔案等。

SqlSessionTemplate是sqlSesson的一個實現,他可以完全代替我們前面所使用的sqlSesson。SqlSessionTemplate 是執行緒安全的,可以被多個 DAO 或對映器所共享使用。

2.5 使用SqlSessionTemplate

我們建立一個UserMapper的實現類UserMapperImpl:

public class UserMapperImpl implements UserMapper {

    private SqlSessionTemplate sqlSessionTemplate;

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    public List<User> getUserList() {
        UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
        return mapper.getUserList();

    }
}

只需要在程式碼中引入SqlSessionTemplate,就可像SqlSession一樣使用它。

建立完成之後記得注入到Spring中,為了把配置和其他的Bean注入分開,我們建立一個applicationContext.xml來統一管理配置檔案:

<?xml version="1.0" encoding="UTF8"?>
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring.xml"/>

    <bean id="userMapper" class="com.javayz.mapper.UserMapperImpl">
        <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
    </bean>

</beans>

2.6 測試

 @org.junit.Test
 public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = (UserMapper) context.getBean("userMapper");
        System.out.println(userMapper.getUserList());
}

直接呼叫mapper即可,不用再像Mybatis一樣先建立SqlSessionFactory,再建立SqlSession。

(三)使用SqlSessionDaoSupport再簡化

有沒有覺得前面使用SqlSessionTemplate還是有些麻煩,官方給我們提供了更加簡單的方式。

使用SqlSessionDaoSupport的話spring-mybatis這個配置檔案就不需要再配置SqlSessionTemplate了

<?xml version="1.0" encoding="UTF8"?>
<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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

        <!--DataSource由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/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </bean>
        <!--配置SqlSessionFactory-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="datasource"/>
            <!--繫結Mybatis配置檔案-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
</beans>

然後我們新建一個UserMapperImpl2,它需要繼承SqlSessionDaoSupport ,然後直接用getSqlSession()獲取到SqlSession即可。

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    public List<User> getUserList() {
        return getSqlSession().getMapper(UserMapper.class).getUserList();
    }
}

最後注入Bean,需要注入sqlSessionFactory屬性:

<bean id="userMapper2" class="com.javayz.mapper.UserMapperImpl2">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

最後測試後獲得同樣的結果。

(四)總結

到這裡差不多把Spring的基本使用都講完了,後續會講一些面試中常考的比較難的知識點,有興趣可以關注一下。