1. 程式人生 > >基於springboot2 框架整合(3):mybatis plus整合

基於springboot2 框架整合(3):mybatis plus整合

前言

專案中使用了很多現成的框架,都是專案經理、架構師帶來的,從來沒有自己整合過!這次決定自己從零開始整合一次,以學習鞏固。過程中參考很多開源框架的思路,工具類等,若有侵權,請速速聯絡,一定妥善處理

 

一:簡介

這裡直接引用官方介紹了“MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生”。官網: http://mp.baomidou.com/

 

二:依賴

<!--mybatis-plus-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.0.4</version>
</dependency>

 

三:配置

application.yml 增加配置如下

#================================================= mybatis-plus start =================================================
mybatis-plus:
  # config-location:
  # classpath:/mapper/*Mapper.xml
  mapper-locations: classpath*:org/itachi/frame/modules/*/mapper/xml/*.xml
  # 實體掃描,多個package用逗號或者分號分隔
  type-aliases-package: org.itachi.frame.modules.*.entity
  configuration:
    # 駝峰下劃線轉換
    map-underscore-to-camel-case: true
    cache-enabled: false
    call-setters-on-nulls: true
  global-config:
    # 重新整理mapper 除錯神器
    refresh: true
    banner: false
    #資料庫大寫下劃線轉換
    #capital-mode: true
    #序列介面實現類配置
    #key-generator: com.baomidou.springboot.xxx
    # 資料庫相關配置
    db-config:
      db-type: mysql
      # 主鍵型別  AUTO:"資料庫ID自增", INPUT:"使用者輸入ID",ID_WORKER:"全域性唯一ID (數字型別唯一ID)", UUID:"全域性唯一ID UUID";
      id-type: UUID
      # 欄位策略 IGNORED:"忽略判斷",NOT_NULL:"非 NULL 判斷"),NOT_EMPTY:"非空判斷"
      field-strategy: not_empty
      capital-mode: true
      #邏輯刪除配置
      logic-delete-value: 1
      logic-not-delete-value: 0
#================================================= mybatis-plus end ===================================================

 

配置分頁外掛

MyBatisPlusConfig.java

package org.itachi.frame.core.config.db;

import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * mybatis-plus 配置
 *
 * @author itachi
 * @date 2018-10-05 17:40
 */
@Configuration
@MapperScan("org.itachi.frame.modules.*.mapper")
public class MyBatisPlusConfig {

    /**
     * 分頁外掛
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

 

四:業務程式碼

 

資料表指令碼 u_user.sql

CREATE TABLE `u_user` (
  `id` char(64) NOT NULL COMMENT '主鍵',
  `name` varchar(255) DEFAULT NULL COMMENT '姓名',
  `age` int(255) DEFAULT NULL COMMENT '年齡',
  `gender` varchar(255) DEFAULT NULL COMMENT '性別',
  `address` varchar(255) DEFAULT NULL COMMENT '地址',
  `head_img` varchar(255) DEFAULT NULL COMMENT '頭像',
  `del_flag` tinyint(1) DEFAULT '0' COMMENT '刪除標誌',
  `amount` decimal(10,2) DEFAULT NULL COMMENT '存款',
  `create_date` datetime DEFAULT NULL COMMENT '建立日期',
  `update_date` datetime DEFAULT NULL COMMENT '修改時間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='使用者';

 

實體User.java

這裡使用了lombok,不寫setter getter相當的爽

package org.itachi.frame.modules.user.entity;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 使用者實體
 *
 * @author itachi
 * @date 2018-10-05 16:48
 */
@Data
@TableName("u_user")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 主鍵
     */
    private String id;

    /**
     * 姓名
     */
    private String name;

    /**
     * 年齡
     */
    private Integer age;

    /**
     * 性別
     */
    private String gender;

    /**
     * 地址
     */
    private String address;

    /**
     * 頭像
     */
    private String headImg;

    /**
     * 存款
     */
    private BigDecimal amount;

    @TableLogic
    private Integer delFlag;

    @TableField(fill = FieldFill.INSERT)
    private Date createDate;

    @TableField(fill = FieldFill.UPDATE)
    private Date updateDate;
}

 

UserMapper.java

package org.itachi.frame.modules.user.mapper;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.itachi.frame.modules.user.entity.User;
import org.itachi.frame.modules.user.pojo.UserQuery;

import java.util.List;

/**
 * 使用者 Mapper 介面
 *
 * @author itachi
 * @date 2018-10-05 16:51
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {

    /**
     * 查詢分頁列表
     *
     * @author itachi
     * @date 2018-10-05 17:25
     */
    List<User> queryPage(Page page, @Param("user") UserQuery userQuery);
}

 

UserMapper.java

<?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="org.itachi.frame.modules.user.mapper.UserMapper">

    <!-- 通用查詢對映結果 -->
    <resultMap id="BaseResultMap" type="org.itachi.frame.modules.user.entity.User">
        <id column="id" property="id"/>
        <result column="del_flag" property="delFlag"/>
        <result column="create_date" property="createDate"/>
        <result column="update_date" property="updateDate"/>
        <result column="name" property="name"/>
        <result column="age" property="age"/>
        <result column="gender" property="gender"/>
        <result column="address" property="address"/>
        <result column="head_img" property="headImg"/>
        <result column="amount" property="amount"/>
    </resultMap>

    <!-- 通用查詢結果列 -->
    <sql id="Base_Column_List">
        del_flag,
        create_date,
        update_date,
        id, name, age, gender, address, head_img, amount
    </sql>

    <select id="queryPage" resultType="org.itachi.frame.modules.user.entity.User">
        select * from u_user
        <where>
            <if test="user.name !=null and user.name != ''">
                name = #{user.name}
            </if>
        </where>
    </select>

</mapper>

 

IUserService.java

package org.itachi.frame.modules.user.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import org.itachi.frame.modules.user.entity.User;
import org.itachi.frame.modules.user.pojo.UserQuery;

/**
 * 使用者 服務類
 *
 * @author itachi
 * @date 2018-10-05 17:00
 */
public interface IUserService extends IService<User> {
   
    boolean delete(String ... ids);

    Page queryPage(UserQuery userQuery);
}

 

UserServiceImpl.java

package org.itachi.frame.modules.user.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.itachi.frame.modules.user.entity.User;
import org.itachi.frame.modules.user.mapper.UserMapper;
import org.itachi.frame.modules.user.pojo.UserQuery;
import org.itachi.frame.modules.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 使用者 服務實現類
 *
 * @author itachi
 * @date 2018-10-05 17:01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String... ids) {
        for (String id : ids) {
            removeById(id);
            //int i = 1/0;
        }
        return true;
    }

    @Override
    public Page queryPage(UserQuery userQuery) {
        Page page = new Page(1, 10);
        page.setRecords(userMapper.queryPage(page, userQuery));

        return page;
    }
}

 

UserController.java

package org.itachi.frame.modules.user.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.itachi.frame.modules.user.pojo.UserQuery;
import org.itachi.frame.modules.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 使用者 控制器
 *
 * @author itachi
 * @date 2018-10-05 17:10
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;

    @GetMapping("/queryPage")
    public Object queryPage(UserQuery userQuery) {
        Page page = userService.queryPage(userQuery);
        return page;
    }
}

 

UserQuery.java

package org.itachi.frame.modules.user.pojo;

import lombok.Data;

/**
 * 使用者查詢物件封裝
 *
 * @author itachi
 * @date 2018-10-05 16:53
 */
@Data
public class UserQuery {
    /**
     * 姓名
     */
    private String name;
}

 

目錄結構如下

五:測試

訪問http://localhost:8080/user/queryPage成功。至此,mybatis plus基本整合完成

 

mybatis plus還有很多強大的功能,如查詢構造器,邏輯刪除,公共欄位填充等,更多參考官網:http://mp.baomidou.com/