Mybatis-Plus BaseMapper的用法详解

1、如何使用BaseMapper进行数据库的操作。

2、使用BaseMapper进行插入实体时如何让UUID的主键自动生成。

Student实体类,其中id属性主键为UUID

package com.huixiaoer.ant.api.model.bean;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;

public class Student {
  /**
   *
   * This field was generated by MyBatis Generator.
   * This field corresponds to the database column student.id
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  @TableId(type= IdType.UUID)
  private String id;

  /**
   *
   * This field was generated by MyBatis Generator.
   * This field corresponds to the database column student.user_name
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  private String userName;

  /**
   *
   * This field was generated by MyBatis Generator.
   * This field corresponds to the database column student.age
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  private Integer age;

  /**
   *
   * This field was generated by MyBatis Generator.
   * This field corresponds to the database column student.phone
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  private String phone;

  /**
   * This method was generated by MyBatis Generator.
   * This method corresponds to the database table student
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  public Student(String id, String userName, Integer age, String phone) {
    this.id = id;
    this.userName = userName;
    this.age = age;
    this.phone = phone;
  }

  /**
   * This method was generated by MyBatis Generator.
   * This method corresponds to the database table student
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  public Student() {
    super();
  }

  /**
   * This method was generated by MyBatis Generator.
   * This method returns the value of the database column student.id
   *
   * @return the value of student.id
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  public String getId() {
    return id;
  }

  /**
   * This method was generated by MyBatis Generator.
   * This method sets the value of the database column student.id
   *
   * @param id the value for student.id
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  public void setId(String id) {
    this.id = id == null ? null : id.trim();
  }

  /**
   * This method was generated by MyBatis Generator.
   * This method returns the value of the database column student.user_name
   *
   * @return the value of student.user_name
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  public String getUserName() {
    return userName;
  }

  /**
   * This method was generated by MyBatis Generator.
   * This method sets the value of the database column student.user_name
   *
   * @param userName the value for student.user_name
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  public void setUserName(String userName) {
    this.userName = userName == null ? null : userName.trim();
  }

  /**
   * This method was generated by MyBatis Generator.
   * This method returns the value of the database column student.age
   *
   * @return the value of student.age
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  public Integer getAge() {
    return age;
  }

  /**
   * This method was generated by MyBatis Generator.
   * This method sets the value of the database column student.age
   *
   * @param age the value for student.age
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  public void setAge(Integer age) {
    this.age = age;
  }

  /**
   * This method was generated by MyBatis Generator.
   * This method returns the value of the database column student.phone
   *
   * @return the value of student.phone
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  public String getPhone() {
    return phone;
  }

  /**
   * This method was generated by MyBatis Generator.
   * This method sets the value of the database column student.phone
   *
   * @param phone the value for student.phone
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  public void setPhone(String phone) {
    this.phone = phone == null ? null : phone.trim();
  }
}

StudnetVI实体类,用户从页面接收参数

package com.huixiaoer.ant.api.model.vi;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(value = "student对象",description = "学生对象student")
public class StudentVI {

  /**
   *
   * This field was generated by MyBatis Generator.
   * This field corresponds to the database column student.user_name
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  @ApiModelProperty(value="学生姓名",name="userName",required=true)
  private String userName;

  /**
   *
   * This field was generated by MyBatis Generator.
   * This field corresponds to the database column student.age
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  @ApiModelProperty(value="年龄",name="age",required=true)
  private Integer age;

  /**
   *
   * This field was generated by MyBatis Generator.
   * This field corresponds to the database column student.phone
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  @ApiModelProperty(value="手机号",name="phone",required=true)
  private String phone;

  public String getUserName() {
    return userName;
  }

  public void setUserName(String userName) {
    this.userName = userName;
  }

  public Integer getAge() {
    return age;
  }

  public void setAge(Integer age) {
    this.age = age;
  }

  public String getPhone() {
    return phone;
  }

  public void setPhone(String phone) {
    this.phone = phone;
  }

}

StudentPlusMapper接口类,实现BaseMapper用来实现Mybatis-Plus的增强功能。

package com.huixiaoer.ant.api.repository.mysql.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.huixiaoer.ant.api.model.bean.Student;

public interface StudentPlusMapper extends BaseMapper<Student> {
  //不需要实现,这时候就可以调用baseMapper的增删改查了
}

StudentService业务接口类

package com.huixiaoer.ant.api.service;

import com.huixiaoer.ant.api.model.bean.Student;
import com.huixiaoer.ant.api.model.bean.StudentExample;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.SelectKey;

import java.util.List;

public interface StudentService {
  /**
   * This method was generated by MyBatis Generator.
   * This method corresponds to the database table student
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  long countByExample(StudentExample example);

  /**
   * This method was generated by MyBatis Generator.
   * This method corresponds to the database table student
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  int deleteByExample(StudentExample example);

  /**
   * This method was generated by MyBatis Generator.
   * This method corresponds to the database table student
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  @Insert({
    "insert into student (id, user_name, ",
    "age, phone)",
    "values (#{id,jdbcType=VARCHAR}, #{userName,jdbcType=VARCHAR}, ",
    "#{age,jdbcType=INTEGER}, #{phone,jdbcType=VARCHAR})"
  })
  @SelectKey(statement="select uuid_short()", keyProperty="id", before=true, resultType=String.class)
  int insert(Student record);

  /**
   * This method was generated by MyBatis Generator.
   * This method corresponds to the database table student
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  int insertSelective(Student record);

  /**
   * This method was generated by MyBatis Generator.
   * This method corresponds to the database table student
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  List<Student> selectByExample(StudentExample example);

  /**
   * This method was generated by MyBatis Generator.
   * This method corresponds to the database table student
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  int updateByExampleSelective(@Param("record") Student record, @Param("example") StudentExample example);

  /**
   * This method was generated by MyBatis Generator.
   * This method corresponds to the database table student
   *
   * @mbg.generated Thu Oct 31 14:09:39 CST 2019
   */
  int updateByExample(@Param("record") Student record, @Param("example") StudentExample example);
}

StudentServiceImpl业务接口实现类,这里将mybatis-plus的mapper接口注入其中。

package com.huixiaoer.ant.api.service.impl;

import com.huixiaoer.ant.api.model.bean.Student;
import com.huixiaoer.ant.api.model.bean.StudentExample;
import com.huixiaoer.ant.api.repository.mysql.mapper.StudentMapper;
import com.huixiaoer.ant.api.repository.mysql.mapper.StudentPlusMapper;
import com.huixiaoer.ant.api.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class StudentServiceImpl implements StudentService {

  @Autowired
  private StudentMapper studentMapper;

  @Autowired
  private StudentPlusMapper studentPlusMapper;

  @Override
  public long countByExample(StudentExample example) {
    return 0;
  }

  @Override
  public int deleteByExample(StudentExample example) {
    return 0;
  }

  @Override
  public int insert(Student record) {
    return studentPlusMapper.insert(record);
  }

  @Override
  public int insertSelective(Student record) {
    return studentMapper.insertSelective(record);
  }

  @Override
  public List<Student> selectByExample(StudentExample example) {
    return null;
  }

  @Override
  public int updateByExampleSelective(Student record, StudentExample example) {
    return 0;
  }

  @Override
  public int updateByExample(Student record, StudentExample example) {
    return 0;
  }
}

SchoolController类,实现前端和后台的交互。自动注入学生业务实现类。

package com.huixiaoer.ant.api.controller;

import com.huixiaoer.ant.api.common.constant.ResultCode;
import com.huixiaoer.ant.api.model.bean.Student;
import com.huixiaoer.ant.api.model.vi.StudentVI;
import com.huixiaoer.ant.api.service.impl.StudentServiceImpl;
import com.huixiaoer.ant.api.util.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author create by yiqiang.wu
 * @create 2019/06/12
 * @email yiqiang.wu@huixiaoer.com
 * @description 登录
 */
@Slf4j
@RestController
@Api(tags = "学校 相关接口")
public class SchoolController {

  @Autowired
  private StudentServiceImpl studentService;

  @Autowired
  private HttpServletRequest request;

  @ApiOperation(value = "增加学生信息")
  @PostMapping(value = "/insert/student")
  public CommonResult insertStudent(@RequestBody @ApiParam(name="学生对象",value="传入json格式",required=true) StudentVI studentVI) {
    try {
      Student student = new Student();
//      student.setId(UUID.randomUUID().toString());
      student.setUserName(studentVI.getUserName());
      student.setAge(studentVI.getAge());
      student.setPhone(studentVI.getPhone());
      studentService.insert(student);
    } catch (Exception e) {
      System.out.println(e);
      return CommonUtil.buildResponse(ResultCode.SYSTEM_ERROR, ResultCode.SYSTEM_ERROR_MSG);
    }
    return CommonUtil.buildResponse(ResultCode.SUCCESS, ResultCode.SUCCESS_MSG);
  }

}

补充一下Mybatis的xml文件

<?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.huixiaoer.ant.api.repository.mysql.mapper.StudentMapper">
 <resultMap id="BaseResultMap" type="com.huixiaoer.ant.api.model.bean.Student">
  <!--
   WARNING - @mbg.generated
   This element is automatically generated by MyBatis Generator, do not modify.
   This element was generated on Thu Oct 31 14:09:39 CST 2019.
  -->
  <constructor>
   <arg column="id" javaType="java.lang.String" jdbcType="VARCHAR" />
   <arg column="user_name" javaType="java.lang.String" jdbcType="VARCHAR" />
   <arg column="age" javaType="java.lang.Integer" jdbcType="INTEGER" />
   <arg column="phone" javaType="java.lang.String" jdbcType="VARCHAR" />
  </constructor>
 </resultMap>
 <sql id="Example_Where_Clause">
  <!--
   WARNING - @mbg.generated
   This element is automatically generated by MyBatis Generator, do not modify.
   This element was generated on Thu Oct 31 14:09:39 CST 2019.
  -->
  <where>
   <foreach collection="oredCriteria" item="criteria" separator="or">
    <if test="criteria.valid">
     <trim prefix="(" prefixOverrides="and" suffix=")">
      <foreach collection="criteria.criteria" item="criterion">
       <choose>
        <when test="criterion.noValue">
         and ${criterion.condition}
        </when>
        <when test="criterion.singleValue">
         and ${criterion.condition} #{criterion.value}
        </when>
        <when test="criterion.betweenValue">
         and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
        </when>
        <when test="criterion.listValue">
         and ${criterion.condition}
         <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
          #{listItem}
         </foreach>
        </when>
       </choose>
      </foreach>
     </trim>
    </if>
   </foreach>
  </where>
 </sql>
 <sql id="Update_By_Example_Where_Clause">
  <!--
   WARNING - @mbg.generated
   This element is automatically generated by MyBatis Generator, do not modify.
   This element was generated on Thu Oct 31 14:09:39 CST 2019.
  -->
  <where>
   <foreach collection="example.oredCriteria" item="criteria" separator="or">
    <if test="criteria.valid">
     <trim prefix="(" prefixOverrides="and" suffix=")">
      <foreach collection="criteria.criteria" item="criterion">
       <choose>
        <when test="criterion.noValue">
         and ${criterion.condition}
        </when>
        <when test="criterion.singleValue">
         and ${criterion.condition} #{criterion.value}
        </when>
        <when test="criterion.betweenValue">
         and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
        </when>
        <when test="criterion.listValue">
         and ${criterion.condition}
         <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
          #{listItem}
         </foreach>
        </when>
       </choose>
      </foreach>
     </trim>
    </if>
   </foreach>
  </where>
 </sql>
 <sql id="Base_Column_List">
  <!--
   WARNING - @mbg.generated
   This element is automatically generated by MyBatis Generator, do not modify.
   This element was generated on Thu Oct 31 14:09:39 CST 2019.
  -->
  id, user_name, age, phone
 </sql>
 <select id="selectByExample" parameterType="com.huixiaoer.ant.api.model.bean.StudentExample" resultMap="BaseResultMap">
  <!--
   WARNING - @mbg.generated
   This element is automatically generated by MyBatis Generator, do not modify.
   This element was generated on Thu Oct 31 14:09:39 CST 2019.
  -->
  select
  <if test="distinct">
   distinct
  </if>
  <include refid="Base_Column_List" />
  from student
  <if test="_parameter != null">
   <include refid="Example_Where_Clause" />
  </if>
  <if test="orderByClause != null">
   order by ${orderByClause}
  </if>
 </select>
 <delete id="deleteByExample" parameterType="com.huixiaoer.ant.api.model.bean.StudentExample">
  <!--
   WARNING - @mbg.generated
   This element is automatically generated by MyBatis Generator, do not modify.
   This element was generated on Thu Oct 31 14:09:39 CST 2019.
  -->
  delete from student
  <if test="_parameter != null">
   <include refid="Example_Where_Clause" />
  </if>
 </delete>
 <insert id="insertSelective" parameterType="com.huixiaoer.ant.api.model.bean.Student">
  <!--
   WARNING - @mbg.generated
   This element is automatically generated by MyBatis Generator, do not modify.
   This element was generated on Thu Oct 31 14:09:39 CST 2019.
  -->
  <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
   select uuid_short()
  </selectKey>
  insert into student
  <trim prefix="(" suffix=")" suffixOverrides=",">
   id,
   <if test="userName != null">
    user_name,
   </if>
   <if test="age != null">
    age,
   </if>
   <if test="phone != null">
    phone,
   </if>
  </trim>
  <trim prefix="values (" suffix=")" suffixOverrides=",">
   #{id,jdbcType=VARCHAR},
   <if test="userName != null">
    #{userName,jdbcType=VARCHAR},
   </if>
   <if test="age != null">
    #{age,jdbcType=INTEGER},
   </if>
   <if test="phone != null">
    #{phone,jdbcType=VARCHAR},
   </if>
  </trim>
 </insert>
 <select id="countByExample" parameterType="com.huixiaoer.ant.api.model.bean.StudentExample" resultType="java.lang.Long">
  <!--
   WARNING - @mbg.generated
   This element is automatically generated by MyBatis Generator, do not modify.
   This element was generated on Thu Oct 31 14:09:39 CST 2019.
  -->
  select count(*) from student
  <if test="_parameter != null">
   <include refid="Example_Where_Clause" />
  </if>
 </select>
 <update id="updateByExampleSelective" parameterType="map">
  <!--
   WARNING - @mbg.generated
   This element is automatically generated by MyBatis Generator, do not modify.
   This element was generated on Thu Oct 31 14:09:39 CST 2019.
  -->
  update student
  <set>
   <if test="record.id != null">
    id = #{record.id,jdbcType=VARCHAR},
   </if>
   <if test="record.userName != null">
    user_name = #{record.userName,jdbcType=VARCHAR},
   </if>
   <if test="record.age != null">
    age = #{record.age,jdbcType=INTEGER},
   </if>
   <if test="record.phone != null">
    phone = #{record.phone,jdbcType=VARCHAR},
   </if>
  </set>
  <if test="_parameter != null">
   <include refid="Update_By_Example_Where_Clause" />
  </if>
 </update>
 <update id="updateByExample" parameterType="map">
  <!--
   WARNING - @mbg.generated
   This element is automatically generated by MyBatis Generator, do not modify.
   This element was generated on Thu Oct 31 14:09:39 CST 2019.
  -->
  update student
  set id = #{record.id,jdbcType=VARCHAR},
   user_name = #{record.userName,jdbcType=VARCHAR},
   age = #{record.age,jdbcType=INTEGER},
   phone = #{record.phone,jdbcType=VARCHAR}
  <if test="_parameter != null">
   <include refid="Update_By_Example_Where_Clause" />
  </if>
 </update>
</mapper>

各种UUID生成策略,生成的UUID值进行比较。

到此这篇关于Mybatis-Plus BaseMapper的用法详解的文章就介绍到这了,更多相关Mybatis-Plus BaseMapper内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 引入mybatis-plus报 Invalid bound statement错误问题的解决方法

    错误 Mybatis-Plus (简称MP) 是mybatis的一个增强工具,在mybatis的基础上只做增强不做改变,简化了开发效率.其实就是帮我们封装了一些简单的curd方法,可以直接调用,不必再重写这些简单的sql语句,类似JPA那样. 前两天创建了一个新项目,持久层框架用的是mybatis,同时引入mybatis-plus做增强工具,项目启动后,调用接口却发现报错了,报错的提醒如下: 错误的信息显示的是 "无效的绑定语句",报错的地方正是操作sql语句的方法,从网上查了一下答案

  • Mybatis-Plus 多表联查分页的实现代码

    上一节,简单讲述了 Mybatis-Plus 搭建与使用入门,这一节,简单讲一下如何使用 MP 实现多表分页. 分析 使用的工程,依旧是 spring-boot,关于分页,官网给出了一个单表的demo,其实多表分页实现原理相同,都是通过 mybatis 的拦截器 (拦截器做了什么?他会在你的 sql 执行之前,为你做一些事情,例如分页,我们使用了 MP 不用关心 limit,拦截器为我们拼接.我们也不用关心总条数,拦截器获取到我们 sql 后,拼接 select count(*) 为我们查询总条

  • 使用mybatis-plus-generator进行代码自动生成的方法

    为了解放程序员的双手,减少重复性代码的编写,推荐使用插件:mybatis-plus-generator 进行代码自动生成.下面我将详细介绍通过mybatis-plus-generator 插件自动生成 controller.service.mapper.serviceImpl相关代码. 项目工程目录总览如下: 1. 使用 idea 创建 maven 项目,引入相关依赖,项目pom文件如下所示: <?xml version="1.0" encoding="UTF-8&qu

  • MyBatis-Plus通过插件将数据库表生成Entiry,Mapper.xml,Mapper.class的方式

    创建maven项目,修改pom.xml文件,如下: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://mave

  • Mybatis-plus实现主键自增和自动注入时间的示例代码

    mybatis-plus依赖导入 <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.2</version> </dependency> 建议使用3.3.0后的版本. 导入mybatis-plus就不用导入mybatis了,冲突! 连接数据库 sp

  • 详解基于Mybatis-plus多租户实现方案

    一.引言 小编先解释一下什么叫多租户,什么场景下使用多租户. 多租户是一种软件架构技术,在多用户的环境下,共有同一套系统,并且要注意数据之间的隔离性. 举个实际例子:小编曾经开发过一套支付宝程序,这套程序应用在不同的小程序上,当使用者访问不同,并且进入相对应的小程序页面,小程序则会把用户相关数据传输到小编这里.在传输的时候需要带上小程序标识(租户ID),以便小编将数据进行隔离. 当不同的租户使用同一套程序,这里就需要考虑一个数据隔离的情况. 数据隔离有三种方案: 1.独立数据库:简单来说就是一个

  • Mybatis-Plus 搭建与使用入门(小结)

    Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发.提高效率而生. 中文文档 :http://baomidou.oschina.io/mybatis-plus-doc/#/ 本文介绍包括 1)如何搭建 2)代码生成(controller.service.mapper.xml) 3)单表的CRUD.条件查询.分页 基类已经为你做好了 一.如何搭建 1. 首先我们创建一个 springboot 工程 --> https:/

  • Mybatis-Plus-AutoGenerator 最详细使用方法

    AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity.Mapper.Mapper XML.Service.Controller 等各个模块的代码,极大的提升了开发效率.可以通过模版等一系列的方式来生成代码,⚠️这个比Mybatis-Generator的更加强大,纯java代码..官方地址:https://mp.baomidou.com/guide/generator.html package com.cikers.p

  • 基于Mybatis-Plus的CRUD的实现

    使用mybatis-plus自动生成了5个模块(xml/bean/mapper/service/controller)的代码,这里练习一下mybatis-plus框架下的CRUD. 还是原先的那个springboot项目. mybatis-plus也是mybatis的增强版,它并未改变mybatis原有功能,只是在传统mybatis原有基础上又新增了一些功能,用以提高开发效率. 比如,在mybatis-plus框架下,项目mapper层接口可通过继承BaseMapper,获取基本的CRUD功能,

  • Mybatis-Plus自动填充的实现示例

    在常用业务中有些属性需要配置一些默认值,MyBatis-Plus提供了实现此功能的插件.在这里修改user表添加 create_time 字段和 update_time 字段,在User类中添加对应属性. 1.为需要自动填充的属性添加注解 @TableField 提供了4种自动填充策略:DEFAULT,默认不处理.INSERT,插入填充字段.UPDATE,更新填充字段.INSERT_UPDATE,插入和更新填充字段. @Data public class User { private Long

随机推荐