1. 程式人生 > >基於SpringBoot的Mybatis-Plus外掛整合

基於SpringBoot的Mybatis-Plus外掛整合

公司剛開發一個ssm架構的專案,同事推薦了mybatis的一個外掛,發現上手容易,高效簡潔。下面是官方的文件: 傳送門請進

我的demo目錄:注意SpringBoot的啟動類的位置

這裡寫圖片描述
1.首先新增pom檔案的依賴:

<!-- mybatis的orm外掛 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatisplus-spring-
            boot-starter</artifactId
>
<version>1.0.4</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.0.7</version> </dependency>

注意: mybatis-plus 自動的維護了mybatis以及mybatis-spring的依賴,在springboot中這三者不能同時的出現,避免版本的衝突,表示:跳進過這個坑。。。

2、application.properties 檔案;

#tomcat\u7F16\u7801
server.port=8081

# salt used for generate token
token-random-salt=restyle@123

# \u6570\u636E\u6E90\u914D\u7F6E
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource
.url=jdbc:mysql://localhost:3306/db_stu_crm?useUnicode=true&characterEncoding=utf8&useSSL=false spring.datasource.username=root spring.datasource.password=root spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 spring.datasource.maxWait=60000 spring.datasource.timeBetweenEvictionRunsMillis=60000 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 spring.datasource.filters=stat,wall,log4j spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml mybatis-plus.typeAliasesPackage=com.cn.restyle.entity
資料來源的配置:

package com.cn.restyle.config;

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * 資料來源配置
 */
@Configuration
public class DataSourceConfig {

    @Bean(name="dataSource")
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource dataSource(){
        return new DruidDataSource();
    } 

    // 配置事物管理器
    @Bean(name="transactionManager") 
    public DataSourceTransactionManager transactionManager(){
        return new DataSourceTransactionManager(dataSource());
    }

}

3、mybatis的配置

package com.cn.restyle.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.baomidou.mybatisplus.plugins.PaginationInterceptor;

@Configuration
//掃描dao或者是Mapper介面
@MapperScan("com.cn.restyle.mapper*")
public class MybatisPlusConfig {
    /**
     * mybatis-plus 分頁外掛
     */

    @Bean
    public PaginationInterceptor paginationInterceptor(){
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType("mysql");
        return page;
    }

}

4、 新建一個Student 的表

package com.cn.restyle.entity;

import java.util.Date;


import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
import com.fasterxml.jackson.annotation.JsonFormat;

@TableName("tb_student")
public class Student {

    @TableId(value="id",type=IdType.AUTO)
    private Integer id;

    @TableField("stu_name")
    private String stuName;

    @TableField("stu_number")
    private String stuNumber;

    private Integer gender;
    private Integer age;

    private String password;

    @TableField("stu_mobile")
    private String stuMobile;

    /**
     * 家長姓名
     */ 
    @TableField("par_name")
    private String parName;

    @TableField("par_mobile")
    private String parMobile;

    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @TableField("create_time")
    private Date createTime;

    @TableField("is_delete")
    private Integer isDelete;

    @TableField("role_id")
    private Integer roleId;



    // setter和getter方法省略


}

注意: 在這兒註解: @TableName(“tb_student”),它是指與資料庫的關聯,意味著表對應的資料庫的表名是tb_student.
再者,另一個註解,@TableFile(exist=false),表示Student類中有的屬性,而對應的屬性在表中沒有這樣的一個欄位

5、 新建dao層介面StudentMapper:

package com.cn.restyle.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.cn.restyle.entity.Student;
/**
* Student 表資料層控制介面
*/

@Repository
public interface StudentMapper extends BaseMapper<Student> {

    List<Student> findAllStudent();

    List<Student> findSomeColumn();

    void deleteById(Integer id);

    void updateByPrimarKeySelective(Student student);

    void saveStudent(Student student);

    List<Student> findAllStudentPage(Pagination page);


    @Select("select * from tb_student where gender = #{gender}")
    @Results({
        @Result(column="stu_name",property="stuName"),
        @Result(column="stu_mobile",property="stuMobile"),
        @Result(column="stu_number",property="stuNumber"),
        @Result(column="par_name",property="parName"),
        @Result(column="par_mobile",property="parMobile"),
        @Result(column="create_time",property="createTime")
    })
    List<Student> findStuByGender(Integer gender);



}

注意 : 如果在xml 中不寫SQL的,可以使用註解的方式在此介面當中直接寫SQL,實體和資料庫表字段不一致,使用@Result註解來對映

6、 新建StudentMapper的配置檔案:

<?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.cn.restyle.mapper.StudentMapper">
    <resultMap id="BaseResultMap" type="com.cn.restyle.entity.Student">
        <id column="id" property="id"></id>
        <result column="stu_name" property="stuName"></result>
        <result column="stu_mobile" property="stuMobile"></result>
        <result column="stu_number" property="stuNumber"></result>
        <result column="create_time" property="createTime"></result>
        <result column="role_id" property="roleId"></result>
        <result column="par_mobile" property="parMobile"></result>
        <result column="par_name" property="parName"></result>
        <result column="is_delete" property="isDelete"></result>
    </resultMap>

    <sql id="base_column_list">
        stu_name,stu_mobile,stu_number,create_time,par_mobile,par_name
    </sql>

    <insert id="insertStudent" parameterType="com.cn.restyle.entity.Student">
        insert into tb_student (stu_name,stu_mobile,stu_number,par_mobile,par_name)
        values
        (#{stuName},#{stuMobile},#{stuNumber},#{parMobile},#{parName})
    </insert>

<!-- 拼接 -->
    <insert id="saveStudent" parameterType="com.cn.restyle.entity.Student">
        insert into tb_student
        <trim prefix="(" suffix=")" suffixOverrides="," >
            <if test="stuName != null">
                stu_name,
            </if>
            <if test="stuMobile">
                stu_mobile,
            </if>
            <if test="stuNumber">
            stu_number,
            </if>
            <if test="roleId">
            role_id,
            </if>
            <if test="parMobile">
            par_mobile,
            </if>
            <if test="parName">
            par_name,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
        <if test="stuName != null">#{stuName},</if>
        <if test="stuMobile != null">#{stuMobile},</if>
        <if test="stuNumber!= null">#{stuNumber},</if>
        <if test="roleId !=null">#{roleId},</if>
        <if test="parMobile != null">#{parMobile},</if>
        <if test="parName !=null">#{parName},</if>
        </trim>
    </insert>

    <delete id="deleteById" parameterType="java.lang.Integer">
        delete from tb_student
        where id = #{id}
    </delete>

    <update id="updateByPrimarKeySelective" parameterType="com.cn.restyle.entity.Student">
        update tb_student
        <set>
            <if test="stuName ! = null">
                stu_name = #{stuName}
            </if>
            <if test="password ! =null">
                password = #{password}
            </if>
            <if test="stuMobile ! = null">
                stu_mobile = #{stuMobile}
            </if>
        </set>
    </update>

    <update id="updateByprimaryKey">
    update tb_student
    set
    stu_name = #{stuName}
    password = #{password}
    stu_mobile = #{stuMobile}

    </update>

    <select id="findSomeColumn" resultMap="BaseResultMap">
        select
        <include refid="base_column_list" />
        from tb_student
    </select>

    <select id="findAllStudent" resultMap="BaseResultMap">
        select * from tb_student
    </select>

    <select id="findAllStudentPage" resultMap="BaseResultMap" resultType="Student">
        select * from tb_student
    </select>


</mapper>

7、新建service層的類StudentService :

package com.cn.restyle.services;

import java.util.List;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.baomidou.mybatisplus.service.IService;
import com.cn.restyle.entity.Student;

public interface StudentService extends IService<Student> {

    List<Student> findAllStudent();
    List<Student> findSomeColumn();

    void deleteById(Integer id);

    void updateByPrimarKeySelective(Student student);

    void saveStudent(Student student);

    Page<Student> findAllStudentPage(Page<Student> page);

    List<Student> findStuByGender(Integer gender);

}

8、service的實現類:

package com.cn.restyle.services.impl;



import java.util.List;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.PackageHelper;
import com.cn.restyle.entity.Student;
import com.cn.restyle.mapper.StudentMapper;
import com.cn.restyle.services.StudentService;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper,Student> 
                                implements StudentService {

    @Override
    public List<Student> findAllStudent() {
        // TODO Auto-generated method stub
        return baseMapper.findAllStudent();
    }

    @Override
    public List<Student> findSomeColumn() {
        // TODO Auto-generated method stub
        return baseMapper.findSomeColumn();
    }

    @Override
    public void deleteById(Integer id) {
        baseMapper.deleteById(id);

    }

    @Override
    public void updateByPrimarKeySelective(Student student) {
        baseMapper.updateById(student);

    }

    @Override
    public void saveStudent(Student student) {
        baseMapper.saveStudent(student);

    }

    @Override
    public Page<Student> findAllStudentPage(Page<Student> page) {
        // TODO Auto-generated method stub
        page.setRecords(baseMapper.findAllStudentPage(page));
        return page;
    }

    @Override
    public List<Student> findStuByGender(Integer gender) {
        // TODO Auto-generated method stub
        return baseMapper.findStuByGender(gender);
    }


}

測試的Controller:

package com.cn.restyle.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cn.restyle.entity.Student;
import com.cn.restyle.services.StudentService;
import com.cn.restyle.util.Result;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/v1/login")
@Slf4j
public class TestController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/register")
    public Result Register(@RequestBody Student student){
        studentService.insert(student);
        return new Result(Result.OK,"儲存成功");
    }

    @RequestMapping("/findAllStudent")
    public Result test1(){
        Result result = new Result();
        List<Student> student = studentService.findAllStudent();
        result.setData(student);
        return result;
    }

    @RequestMapping("findSomeColumn")
    public Result test2(){
        Result result = new Result();
        List<Student> stu = studentService.findSomeColumn();
        result.setData(stu);
        return result;
    }

    @RequestMapping("deleteById/{id}")
    public Result test3(@PathVariable  Integer id){
        Result result = new Result();
        studentService.deleteById(id);
        result.setMsg("刪除成功");
        return result;
    }

    @RequestMapping("updateByPrimarKeySelective")
    public Result test4(@RequestBody Student student){
        Result result = new Result();
        EntityWrapper<Student> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("stu_mobile", student.getStuMobile());
        Student stu = studentService.selectOne(entityWrapper);
        if (null != stu) {
            stu.setParName("my hero");
            stu.setStuName("zxs");
        }
        studentService.updateByPrimarKeySelective(stu);
        result.setData(stu);
        return result;
    }

    @RequestMapping("/saveStudent")
    public Result<Student> test5(@RequestBody Student student){
        Result<Student> result = new Result<Student>();
        studentService.saveStudent(student);
        result.setData(student);

        return result;

    }
    /**
     * 分頁的方法
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @RequestMapping("page/{pageNumber}")
    public Result findAllStuPage(@PathVariable Integer pageNumber,
                                     @RequestParam(defaultValue="6") Integer pageSize){
        Result result = new Result();
        Page page = new Page(pageNumber,pageSize);
        Page<Student> pageStu = studentService.findAllStudentPage(page);
         result.setData(pageStu.getRecords());
        return result;

    }

    @RequestMapping("pageByGender/{pageNumber}")
    public Result findStuByGender(@PathVariable Integer pageNumber,
            @RequestParam(defaultValue="6") Integer pageSize){
        Result result = new Result<>();

        EntityWrapper<Student> wrapper = new EntityWrapper<>();
        wrapper.eq("gender", 1);
        Page<Student> page = getPage(pageNumber, pageSize);
        Page<Student> stuPage = studentService.selectPage(page, wrapper);
        result.setData(stuPage.getRecords());

        return result;
    }



    /**
     * 獲取分頁物件
     * 每頁顯示數量
     */

    private <T> Page<T> getPage(int pageNum,int pageSize){

        return new Page<T>(pageNum,pageSize);
    }


}

SpringBoot的啟動類:

package com.cn.restyle;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.cn.restyle.mapper")  //配置mapper掃描
@SpringBootApplication
public class CrmApplication {

    public static void main(String[] args) {
        SpringApplication.run(CrmApplication.class, args);
    }
}

另外,對於EntityWrapper的條件拼接,基本可以實現SQL中常用的where,and,or,groupby, orderby等語法

@Test
    public void testSql(String str){
        EntityWrapper<Student> wrapper = new EntityWrapper<>();
        wrapper.eq("stu_name", str)
               .or()
               .eq("par_name", str)
               .orderBy("create_time", false)   // 時間的倒敘排列
               .limit(0, 1);                    // 取一條
        Student stu = studentService.selectOne(wrapper);
    }

附:
我的Result 工具類

package com.cn.restyle.util;

public class Result<T> {
    public static final Integer OK = 0;
    public static final Integer Error = -1;

    private Integer code;
    private String msg;
    private T data;

    public Result(){
        this.code = OK;
        this.msg = "success";
    }

    public Result(Integer code, String msg) {
        super();
        this.code = code;
        this.msg = msg;
    }

    public Result(String msg, T data) {
        super();
        this.msg = msg;
        this.data = data;
    }

    public Result(Integer code, String msg, T data) {
        super();
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }




}

參考文件: