1. 程式人生 > 實用技巧 >SpringBoot整合MyBatis

SpringBoot整合MyBatis

首先引入依賴包:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</
artifactId> <version>2.0.0</version> </dependency>
View Code

註解版:

1.通過yml檔案配置引數

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
    username: root
    password: 12345678
    driver-class-name: com.mysql.cj.jdbc.Driver

2.Mybatis提供了一些註解實現快速CRUD,比如:@Select

,@Update,@Insert,@Delete;

3.SpringBoot整合Mybatis的配置:

  • 方式一:在每個interface Mapper前新增@Mapper註解
  • 方式二:在Application.java啟動類前新增@MapperScan("mapper包所在的位置")註解,每次啟動時會去自動搜尋包

XML的方式

使用Mybatis的XML開發方式應該是我們比較熟悉的,和註解版最大的不同就是Dao層,XML版會自動根據Dao層介面的方法名自動對映到XML中同名id對應的SQL。

1.修改yml檔案

新增如下Mybatis配置屬性

#mybatis配置
mybatis:
  mapper-locations: classpath:mapper/**/*.xml
  type-aliases-package: cn.packge.entity
  configuration:
    # 使用jdbc的getGeneratedKeys 可以獲取資料庫自增主鍵值
    use-generated-keys: true
    map-underscore-to-camel-case: fale  /** 此處為是否開啟駝峰命名 */

然後依次在mapper包下建立xml檔案實現資料庫操作和返回資料對映、建立mapper介面、service、serviceIpml