SpringBoot整合MyBatis教程

SpringBoot整合MyBatis教程

前面兩篇文章和讀者聊了Spring Boot中最簡單的數據持久化方案JdbcTemplate,JdbcTemplate
Spring Boot數據持久化之JdbcTemplate
Spring Boot配置JdbcTemplate之多數據源java

雖然簡單,可是用的並很少,由於它沒有MyBatis方便,在Spring+SpringMVC中整合MyBatis步驟仍是有點複雜的,要配置多個Bean,Spring Boot中對此作了進一步的簡化,使MyBatis基本上能夠作到開箱即用,本文就來看看在Spring Boot中MyBatis要如何使用。mysql

工程建立

首先建立一個基本的Spring Boot工程,添加Web依賴,MyBatis依賴以及MySQL驅動依賴,以下:web

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-ZCZq5Kxx-1588156868106)(http://www.javaboy.org/images/sb/3-1.png)]spring

建立成功後,添加Druid依賴,而且鎖定MySQL驅動版本,完整的依賴以下:sql

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

如此,工程就算是建立成功了。讀者注意,MyBatis和Druid依賴的命名和其餘庫的命名不太同樣,是屬於xxx-spring-boot-stater模式的,這表示該starter是由第三方提供的。數據庫

基本用法

MyBatis的使用和JdbcTemplate基本一致,首先也是在application.properties中配置數據庫的基本信息:apache

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=xiaoliu
spring.datasource.password=960614abcd
spring.datasource.url=jdbc:mysql:///ssm

配置完成後,MyBatis就能夠建立Mapper來使用了,例如我這裏直接建立一個UserMapper,以下:mybatis

package cn.itxiaoliu.mapper;

import cn.itxiaoliu.bean.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;


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

這裏是經過全註解的方式來寫SQL,不寫XML文件,@Select、@Insert、@Update以及@Delete四個註解分別對應XML中的select、insert、update以及delete標籤,@Results註解相似於XML中的ResultMap映射文件(getUserById方法給查詢結果的字段取別名主要是向小夥伴們演示下@Results註解的用法),另外使用@SelectKey註解能夠實現主鍵回填的功能,即當數據插入成功後,插入成功的數據id會賦值到user對象的id屬性上。app

UserMapper建立好以後,還要配置mapper掃描,有兩種方式,一種是直接在UserMapper上面添加@Mapper註解,這種方式有一個弊端就是全部的Mapper都要手動添加,要是落下一個就會報錯,還有一個一勞永逸的辦法就是直接在啓動類上添加Mapper掃描,以下:ide

@SpringBootApplication
@MapperScan(basePackages = "cn.itxiaoliu.mapper")
public class MybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}

好了,作完這些工做就能夠去測試Mapper的使用了。

mapper映射

固然,開發者也能夠在XML中寫SQL,UserMapper.xml以下:

<?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">
<mapper namespace="cn.itxiaoliu.mapper.UserMapper">
    <select id="getAllUser" resultType="cn.itxiaoliu.bean.User">
        select * from user;
    </select>

</mapper>

將接口中方法對應的SQL直接寫在XML文件中。

那麼這個UserMapper.xml到底放在哪裏呢?有兩個位置能夠放,第一個是直接放在UserMapper所在的包下面:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-8P7H4qNl-1588156868111)(http://www.javaboy.org/images/sb/3-2.png)]

放在這裏的UserMapper.xml會被自動掃描到,可是有另一個Maven帶來的問題,就是java目錄下的xml資源在項目打包時會被忽略掉,因此,若是UserMapper.xml放在包下,須要在pom.xml文件中再添加以下配置,避免打包時java目錄下的XML文件被自動忽略掉:

<resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>

固然,UserMapper.xml也能夠直接放在resources目錄下,這樣就不用擔憂打包時被忽略了,可是放在resources目錄下,又不能自動被掃描到,須要添加額外配置。例如我在resources目錄下建立mapper目錄用來放mapper文件,以下:

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-fBjsql9R-1588156868113)(http://www.javaboy.org/images/sb/3-3.png)]

此時在application.properties中告訴mybatis去哪裏掃描mapper:

mybatis.mapper-locations=classpath:mapper/*.xml

如此配置以後,mapper就能夠正常使用了。注意第二種方式不須要在pom.xml文件中配置文件過濾。

原理分析

在SSM整合中,開發者須要本身提供兩個Bean,一個SqlSessionFactoryBean,還有一個是MapperScannerConfigurer,在Spring Boot中,這兩個東西雖然不用開發者本身提供了,可是並不意味着這兩個Bean不須要了,在org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration類中,咱們能夠看到Spring Boot提供了這兩個Bean,部分源碼以下:

@org.springframework.context.annotation.Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration implements InitializingBean {

  @Bean
  @ConditionalOnMissingBean
  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
    factory.setDataSource(dataSource);
    return factory.getObject();
  }
  @Bean
  @ConditionalOnMissingBean
  public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    ExecutorType executorType = this.properties.getExecutorType();
    if (executorType != null) {
      return new SqlSessionTemplate(sqlSessionFactory, executorType);
    } else {
      return new SqlSessionTemplate(sqlSessionFactory);
    }
  }
  @org.springframework.context.annotation.Configuration
  @Import({ AutoConfiguredMapperScannerRegistrar.class })
  @ConditionalOnMissingBean(MapperFactoryBean.class)
  public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {

    @Override
    public void afterPropertiesSet() {
      logger.debug("No {} found.", MapperFactoryBean.class.getName());
    }
  }
}

從類上的註解能夠看出,噹噹前類路徑下存在SqlSessionFactory、 SqlSessionFactoryBean以及DataSource時,這裏的配置纔會生效,SqlSessionFactory和SqlTemplate都被提供了。

相關文章
相關標籤/搜索