1. 程式人生 > >SpringBoot2.X (二十五):SpringBoot整合 Mybatis + MySQL CURD 示例

SpringBoot2.X (二十五):SpringBoot整合 Mybatis + MySQL CURD 示例

話不多數,直接開始擼程式碼…

工程結構圖

開始之前先放張工程結構圖

工程結構圖

1、maven 依賴:

       <!-- Web 依賴-->
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

        <!-- 分頁外掛 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.9</version>
        </dependency>

        <!-- druid 連線池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

2、yml 配置檔案:

spring:
  application:
    name: mybatis-curd

  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&autoReconnect=true
    continue-on-error: true
    sql-script-encoding: UTF-8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 5
      min-idle: 5
      max-active: 20
      max-wait: 60000
      # 間隔多久進行一次檢測,檢測需要關閉的空閒連線
      time-between-eviction-runs-millis: 60000
      # 一個連線在池中最小生存的時間
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 1 FROM DUAL
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      connect-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      use-global-data-source-stat: true
      filters: stat,wall,log4j2

mybatis:
  type-aliases-package: com.fxbin.mybaits.*
  configuration:
    map-underscore-to-camel-case: true
    # 列印sql, 方便除錯
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    use-generated-keys: true
    default-statement-timeout: 60
    default-fetch-size: 100

3、核心程式碼:

User.java
package com.fxbin.mybatis.bean;

import lombok.Data;

import java.util.Date;

/**
 * created with IntelliJ IDEA.
 * author: fxbin
 * date: 2018/10/21
 * time: 5:59
 * version: 1.0
 * description:
 */
@Data
public class User {

    /**
     * 主鍵ID
     */
    private Integer id;

    /**
     * 使用者名稱
     */
    private String username;

    /**
     * 密碼
     */
    private String password;

    /**
     * 建立時間
     */
    private Date gmtCreate;

    /**
     * 修改時間
     */
    private Date gmtModified;

}
MyBatisConfig.java
package com.fxbin.mybatis.config;

import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
 * created with IntelliJ IDEA.
 * author: fxbin
 * date: 2018/10/21
 * time: 11:33
 * version: 1.0
 * description: MyBatis 分頁外掛配置
 */
@Configuration
public class MyBatisConfig {

    @Bean
    public PageHelper pageHelper(){
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();

        // 設定為true時,會將RowBounds第一個引數offset當成pageNum頁碼使用
        p.setProperty("offsetAsPageNum","true");

        //設定為true時,使用RowBounds分頁會進行count查詢
        p.setProperty("rowBoundsWithCount","true");
        p.setProperty("reasonable","true");
        pageHelper.setProperties(p);
        return pageHelper;
    }
}
UserController.java
package com.fxbin.mybatis.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fxbin.mybatis.bean.User;
import com.fxbin.mybatis.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * created with IntelliJ IDEA.
 * author: fxbin
 * date: 2018/10/21
 * time: 5:53
 * version: 1.0
 * description:
 */
@RestController
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 查詢全部
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("/listAll")
    public Object listAll(@RequestParam(value = "page",defaultValue = "1")int page,
                          @RequestParam(value = "size",defaultValue = "10")int size){
        return userService.listAll(page, size);
    }

    /**
     * 新增資料
     * @param user
     * @return
     */
    @RequestMapping("/insert")
    public int insert (User user){
        return userService.insert(user);
    }

    /**
     * 刪除
     * @param userId
     * @return
     */
    @RequestMapping("/remove")
    public int remove(Integer userId){
        return userService.remove(userId);
    }

    /**
     * 修改
     * @param user
     * @return
     */
    @RequestMapping("/update")
    public int update(User user){
        return userService.update(user);
    }
}
UserService.java
package com.fxbin.mybatis.service;

import com.fxbin.mybatis.bean.User;

import java.util.List;

/**
 * created with IntelliJ IDEA.
 * author: fxbin
 * date: 2018/10/21
 * time: 5:54
 * version: 1.0
 * description:
 */
public interface UserService {

    Object listAll(int page, int size);

    int insert(User user);

    int remove(Integer userId);

    int update(User user);
}
UserServiceImpl.java
package com.fxbin.mybatis.service.impl;

import com.fxbin.mybatis.bean.User;
import com.fxbin.mybatis.mapper.UserMapper;
import com.fxbin.mybatis.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * created with IntelliJ IDEA.
 * author: fxbin
 * date: 2018/10/21
 * time: 5:54
 * version: 1.0
 * description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public Object listAll(int page, int size) {
        PageHelper.startPage(page, size);
        List<User> userList = userMapper.listAll();
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        return pageInfo;
    }

    @Override
    public int insert(User user) {
        return userMapper.insert(user);
    }

    @Override
    public int remove(Integer userId) {
        return userMapper.remove(userId);
    }

    @Override
    public int update(User user) {
        return userMapper.update(user);
    }
}
UserMapper.java
package com.fxbin.mybatis.mapper;

import com.fxbin.mybatis.bean.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * created with IntelliJ IDEA.
 * author: fxbin
 * date: 2018/10/21
 * time: 5:55
 * version: 1.0
 * description:
 */
@Mapper
public interface UserMapper {

    @Select({
            "select * from user"
    })
    List<User> listAll();

    @Insert({
            "insert into user(`username`, `password`) values(#{username}, #{password})"
    })
    int insert(User user);

    @Delete({
            "delete from user where id = #{userId}"
    })
    int remove(Integer userId);

    @Update({
            "update user set username = #{username}, password = #{password} where id = #{id}"
    })
    int update(User user);
}

4、測試

1)、查詢

在這裡插入圖片描述

2)新增

在這裡插入圖片描述

檢視資料庫記錄,進一步驗證,確實已經新增了一條記錄 在這裡插入圖片描述

3)移除

在這裡插入圖片描述

檢視資料庫,id 為1 的記錄已經成功移除

在這裡插入圖片描述

4)修改

我們修改之前新增的id為13 的記錄,username 修改為 “修改”,password 修改為 “222” 在這裡插入圖片描述

檢視資料庫修改記錄,已成功

在這裡插入圖片描述

總結:

以上就是有關 SpringBoot2.X 整合 Mysql + Mybatis 的 CURD 的簡單案例,這裡我沒有對返回結果進行封裝,各位可根據自行需要,進行返回結果的封裝…

— end —

如有問題,請及時聯絡,謝謝