07.深刻淺出 Spring Boot - 數據訪問之Mybatis(附代碼下載)

MyBatis 在Spring Boot應用很是廣,很是強大的一個半自動的ORM框架。html

1、什麼是MyBatis

  1. 支持定製化 SQL、存儲過程以及高級映射的優秀的持久層框架java

  2. 避免了幾乎全部的 JDBC 代碼和手動設置參數以及獲取結果集mysql

  3. 能夠對配置和原生Map使用簡單的 XML 或註解git

  4. 將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄github

  5. 數據庫、數據源、數據庫鏈接池、JDBC、JDBC實現是什麼關係?web

  • JDBC:Java和關係型數據庫的橋樑,是一個規範,不是實現。不一樣類型的數據庫須要有本身的JDBC實現
  • 數據源:包含數據庫鏈接池,鏈接池管理。常見的有C3P0、HikariDataSoiurce、Druid等
  • 鏈接池:預先建立一些數據庫鏈接,放到鏈接池裏面,用的時候從鏈接池裏面取,用完後放回鏈接池
  • 鏈接池管理:建立數據庫鏈接,管理數據庫鏈接
  • JDBC實現:MySQL JDBC實現、Oracle JDBC實現等其餘實現
  • MyBatis對JDBC進行了封裝

2、整合MyBatis

咱們基於以前建立的項目spring-boot-06-data-druid 來建立spring-boot-07-data-mybatis項目spring

1)引入MyBatis依賴sql

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

2)引入其餘依賴數據庫

<dependencies>
  <!-- web -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <!-- mysql -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
  </dependency>

  <!-- swagger -->
  <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
  </dependency>
  <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
  </dependency>

  <!-- Druid -->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
  </dependency>

3)依賴圖小程序

3、用註解方式使用 MyBatis

1.準備建立department表的腳本

DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `department_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

2.application.yml 自動執行腳本

initialization-mode: always
schema:
  - classpath:department.sql

執行一次後,註釋 initialization-mode

# initialization-mode: always

3.建立department 實體類

package com.jackson0714.springboot.entity;

public class Department {
    private Long id;
    private String departmentName;

    public void setId(Long id) {
        this.id = id;
    }

    public Long getId() {
        return id;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    public String getDepartmentName() {
        return departmentName;
    }
}

4.建立Mapper映射類,並將SQL註解到方法上

增刪改查,你要的都在這裏:

@Mapper
public interface DepartmentMapper {

    @Select("select * from department")
    List<Map<String, Object>> getAllDepartment();

    @Select("select * from department where id=#{id}")
    Department getDepartmentById(Long id);

    @Delete("delete from department where id=#{id}")
    int deleteDepartment(Long id);

    @Insert("insert into department(department_name) values(#{departmentName})")
    int createDepartment(String departmentName);

    @Update("update department set department_name=#{departmentName} where id=#{id}")
    int updateDepartmentById(Long id, String departmentName);
}

5.建立MyBatis 配置類

增長自定義配置:若是表的字段名有下劃線格式的,轉爲駝峯命名格式

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(Configuration configuration) {
                // 若是表的字段名有下劃線格式的,轉爲駝峯命名格式
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

6.建立DepartmentController

@Api(value = "DepartmentController", description = "部門controller")
@RequestMapping("/v1/client")
@RestController
public class DepartmentController {

    @Autowired
    DepartmentMapper departmentMapper;

    @ApiOperation(value = "1.查詢全部部門")
    @GetMapping("/dept/getAllDepartment")
    public List<Map<String, Object>> getAllDepartment() {
        return departmentMapper.getAllDepartment();
    }

    @ApiOperation(value = "2.根據id查詢某個部門")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "須要查詢的部門id")
    })
    @GetMapping("/dept/{id}")
    public Department getDepartmentById(@PathVariable Long id) {
        return departmentMapper.getDepartmentById(id);
    }

    @ApiOperation(value = "3.新增部門")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "部門名稱")
    })
    @PostMapping("/dept/create")
    public int createDepartment(@RequestParam String name) {
        return departmentMapper.createDepartment(name);
    }

    @ApiOperation(value = "4.根據id刪除部門")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "須要刪除的部門id")
    })
    @PostMapping("/dept/delete")
    public int deleteDepartment(@RequestParam Long id) {
        return departmentMapper.deleteDepartment(id);
    }

    @ApiOperation(value = "5.根據id更新部門名稱")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "須要更新的部門id"),
            @ApiImplicitParam(name = "name", value = "須要更新的部門名稱")
    })
    @PostMapping("/dept/update")
    public int updateDepartmentById(@RequestParam Long id, @RequestParam String name) {
        return departmentMapper.updateDepartmentById(id, name);
    }
}

使用Swagger來測試

4、用配置方式使用 MyBatis

1. 文件結構

2. 建立user表的腳本

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵ID',
  `user_name` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '用戶名',
  `password` varchar(255) COLLATE utf8mb4_bin NOT NULL,
  `salt` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '隨機鹽',
  `nickName` varchar(255) COLLATE utf8mb4_bin NOT NULL COMMENT '用戶名',
  `phone` varchar(20) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '手機號',
  `avatar` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '頭像',
  `mini_openId`  varchar(32) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '小程序OpenId',
  `lock_flag` char(1) COLLATE utf8mb4_bin DEFAULT '0' COMMENT '0-正常,9-鎖定',
  `del_flag` char(1) COLLATE utf8mb4_bin DEFAULT '0' COMMENT '0-正常,1-刪除',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間',
  PRIMARY KEY (`user_id`),
  KEY `user_wx_openid` (`mini_openId`),
  KEY `user_idx1_username` (`user_name`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='用戶表';

3. 插入一條User數據

INSERT INTO user(user_name, password, nick_name, phone) values ("jackson0714", "123", "悟空聊架構", "123456")

4. 建立User實體類

package com.jackson0714.springboot.entity;

import lombok.Data;

import java.sql.Timestamp;

@Data
public class User {

    private Long userId;
    private String userName;
    private String password;
    private String salt;
    private String nickName;
    private String phone;
    private String avatar;
    private String miniOpenId;
    private String openId;
    private Boolean lockFlag;
    private Boolean delFlag;
    private Timestamp createTime;
    private Timestamp updateTime;
}

須要安裝Lombok插件

須要引入Lombok依賴

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.18.12</version>
  <scope>provided</scope>
</dependency>

5. 建立調用User方法的 UserMapper 接口

// @Mapper 或MapperScan 將接口掃描裝配到裝配容器中
public interface UserMapper {
    User getUserById(Long userId);
}

6. 建立接口方法與SQL腳本的映射文件

<?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.jackson0714.springboot.mapper.UserMapper">
    <select id="getUserById" resultType="com.jackson0714.springboot.entity.User">
        SELECT * FROM user WHERE user_id=#{userId}
    </select>
</mapper>

7. 建立UserController文件

@Api(value = "UserController", description = "用戶controller")
@RequestMapping("/v1/client")
@RestController
public class UserController {

    @Autowired
    UserMapper userMapper;

    @ApiOperation(value = "1.根據id查詢某個用戶")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "須要查詢的用戶userId", value = "須要查詢的用戶userId")
    })
    @GetMapping("/emp/{userId}")
    public User getUser(@PathVariable("userId") Long userId) {
        return userMapper.getUserById(userId);
    }
}

8. 添加MapperScan註解

@MapperScan(value = "com.jackson0714.springboot.mapper")
@SpringBootApplication
public class Springboot07DataMybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(Springboot07DataMybatisApplication.class, args);
    }
}

9.在Swagger上測試

10. 查看Druid監控

Spring Boot 整合MyBatis 講完了,持續更新 《深刻淺出 Spring Boot 系列》

關注公衆號:悟空聊架構, 回覆pmp,領取pmp資料! 回覆悟空,領取架構師資料!

關注我,帶你天天進步一點點!

原文出處:https://www.cnblogs.com/jackson0714/p/spring-boot-07-mybatis.html

相關文章
相關標籤/搜索