SpringBoot數據訪問之整合Mybatis配置文件


環境搭建以及前置知識回顧

SpringBoot中有兩種start的形式:

  1. 官方:spring-boot-starter-*
  2. 第三方:*-spring-boot-starter

Mybatis屬於第三方,所以我們需要找他的官網、配置文檔等。

貼心鏈接:Github

進入后記得切換tags

image-20210807212729133

作者使用的版本是最新的2.2.0;

找到它下面的pom.xml,可以得到:

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

在網頁下方,找到快速開始文檔

image-20210807212955460

回顧前面mybatis的使用過程:

  1. 導入mybatis依賴和數據庫驅動
  2. 連接數據庫
  3. 增加全局配置文件,一般是(mybatis-config.xml)
  4. 編寫工具類:SqlSessionFactory
  5. 使用sqlSession
  6. 編寫Mapper
  7. .......

Druid的配置:Druid

分析Mybatis啟動器自動配置

找到MybatisAutoConfiguration,

@ConditionalOnSingleCandidate(DataSource.class)

只允許一個數據源在容器中。

@EnableConfigurationProperties(MybatisProperties.class)

@EnableConfigurationProperties(類.class)

  1. 開啟類配置綁定功能
  2. 把這個類這個組件自動注冊到容器中

我們進入MybatisProperties.class中查看:

image-20210807215542241

由上圖可知,我們只需要在配置文件中使用mybatis為前置,就可以使用了。

使用配置搞清楚后,我們來看下啟動器給我們自動裝配了什么功能:

  1. @Bean
    @ConditionalOnMissingBean 
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource)
    

    對應的是之前的使用過程第4步,現在自動配置好了

  2. @Bean
    @ConditionalOnMissingBean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory)
    

    對應之前的使用過程第5步,可以進入**SqlSessionTemplate **看下,SqlSessionTemplate組合了SqlSession。

  3. @Import(AutoConfiguredMapperScannerRegistrar.class),只要我們寫的操作MyBatis的接口,標注了 @Mapper 就會被自動掃描進來,對應之前的使用過程第6步。

整合Mybatis

Mybatis官方文檔

目錄結構:

image-20210808135256604

首先創建一個全局配置文件(mybatis-config.xml):

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

</configuration>

Configuration中包含:包括獲取數據庫連接實例的數據源(DataSource)以及決定事務作用域和控制方式的事務管理器(TransactionManager)。因為我們的數據源已經通過Druid配置好了,所以這里直接清空就好。

實體類

創建實體類,盡可能與數據庫字段名保持一致。

import lombok.Data;

@Data
public class User {
    private int id;
    private String username;
    private String password;
}

Mapper層(對照Dao)

創建GetUserMapper接口;

import com.xbhog.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface GetUserMapper {
    public User getUserid(int id);
}

實現接口:

創建getUserMapper.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="com.xbhog.Mapper.GetUserMapper">

    <select id="getUserid" resultType="com.xbhog.pojo.User">
        select * from user where id = #{id}
    </select>
</mapper>

其中id對應的是GetUserMapper接口中抽象方法getUserid,結果集類型對應的返回值類型User。

其實我們現在可以創建controller來實現訪問了,為了方便后序功能的擴展,我們可以創建一個service層,有一句話說的好,出現問題,沒有加一層解決不了的,有的話那就再加一層。

Service層:DemoService

import com.xbhog.Mapper.GetUserMapper;
import com.xbhog.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class DemoService {
    @Autowired
    GetUserMapper getUserMapper;

    public User getUser(int id){
        return getUserMapper.getUserid(id);
    }
}

從容器中取出GetUserMapper,在service層進行調用。如果只是測試,可以直接省略創建Controller.

創建Controller:

@Controller
public class Mycontro {
    @Autowired
    DemoService demoService;

    @ResponseBody
    @GetMapping("/user")
    public User getById(@RequestParam("id") int id){
        return demoService.getUser(id);
    }

}

上述步驟完成后需要在mybatis中注冊,在Springboot中需要在配置文件中:

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml   #全局配置文件位置
  mapper-locations: classpath:mybatis/Mapper/*.xml #sql映射文件位置

完整配置:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/vuesite
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    druid:
      aop-patterns: com.xbhog.*
      filters: stat,wall
      stat-view-servlet:
        enabled: true
        login-password: admin
        login-username: admin
        reset-enable: false


      web-stat-filter:
        enabled: true
        url-pattern: /*
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'

      filter:
        stat:
          slow-sql-millis: 1000
          log-slow-sql: true
          enabled: true
        wall:
          enabled: true
          config:
            drop-table-allow: false


mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/Mapper/*.xml

測試:

輸入:localhost:8080/user?id=2 查詢id為2的用戶

結果:

{"id":2,"username":"demo","password":"123456"}

如果之前也配置了Druid,可以查看http://localhost:8080/druid/

image-20210808144639346

注意點

駝峰命名:

如果數據庫中的字段是駝峰命名(Camel-Case),那么我們需要在mybatis中開啟駝峰命名,不開啟的話,是無法查找到對應的數據。

在全局配置文件中:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

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

全局配置設置:

其實在springBoot中的mybatis-start中已經有全局配置屬性了。

找到MybatisProperties配置屬性類。

image-20210808145339271

進入Configuration,發現我們需要的配置已經在里面設置好了,以后只需要在配置文件中設置屬性即可:

image-20210808145438077

所以我們可以刪除全局配置文件。在yaml或者properties中配置:

mybatis:
#  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/Mapper/*.xml
  configuration:  #全局配置文件
    map-underscore-to-camel-case: true

總結mybatis整合過程:

  • 導入mybatis官方starter

  • 編寫mapper接口。標准@Mapper注解

  • 編寫sql映射文件並綁定mapper接口

  • 在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息 (建議;配置在mybatis.configuration)

結束:

如果你看到這里或者正好對你有所幫助,希望能點個關注或者推薦,感謝;

有錯誤的地方,歡迎在評論指出,作者看到會進行修改。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM