开发工具:STS

代码下载链接:GitHub管理代码

版本:

  Springboot:1.5.14.RELEASE

    使用2.0以上的Springboot,会报出一些异常。欢迎知道异常原因的大牛解惑。

  MybatisPlus:2.3

前言:

MP扩展了Mybatis对实体的一些简单的CRUD操作,我们不需要再去实现,只要在mapper接口中继承BaseMapper就可以了。

搭建框架可以参考:1、SpringBoot+MybatisPlus整合

开始测试:

BaseMapper<T>:

/**
* Copyright (c) 2011-2020, hubin (jobob@qq.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.baomidou.mybatisplus.mapper; import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map; import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds; /**
* <p>
* Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
* </p>
* <p>
* 这个 Mapper 支持 id 泛型
* </p>
*
* @author hubin
* @Date 2016-01-23
*/
public interface BaseMapper<T> { /**
* <p>
* 插入一条记录
* </p>
*
* @param entity 实体对象
* @return int
*/
Integer insert(T entity); /**
* <p>
* 插入一条记录
* </p>
*
* @param entity 实体对象
* @return int
*/
Integer insertAllColumn(T entity); /**
* <p>
* 根据 ID 删除
* </p>
*
* @param id 主键ID
* @return int
*/
Integer deleteById(Serializable id); /**
* <p>
* 根据 columnMap 条件,删除记录
* </p>
*
* @param columnMap 表字段 map 对象
* @return int
*/
Integer deleteByMap(@Param("cm") Map<String, Object> columnMap); /**
* <p>
* 根据 entity 条件,删除记录
* </p>
*
* @param wrapper 实体对象封装操作类(可以为 null)
* @return int
*/
Integer delete(@Param("ew") Wrapper<T> wrapper); /**
* <p>
* 删除(根据ID 批量删除)
* </p>
*
* @param idList 主键ID列表
* @return int
*/
Integer deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList); /**
* <p>
* 根据 ID 修改
* </p>
*
* @param entity 实体对象
* @return int
*/
Integer updateById(@Param("et") T entity); /**
* <p>
* 根据 ID 修改
* </p>
*
* @param entity 实体对象
* @return int
*/
Integer updateAllColumnById(@Param("et") T entity); /**
* <p>
* 根据 whereEntity 条件,更新记录
* </p>
*
* @param entity 实体对象
* @param wrapper 实体对象封装操作类(可以为 null)
* @return
*/
Integer update(@Param("et") T entity, @Param("ew") Wrapper<T> wrapper); /**
* <p>
* 根据 whereEntity 条件,更新记录
* </p>
*
* @param setStr set字符串
* @param wrapper 实体对象封装操作类(可以为 null)
* @return
*/
Integer updateForSet(@Param("setStr") String setStr, @Param("ew") Wrapper<T> wrapper); /**
* <p>
* 根据 ID 查询
* </p>
*
* @param id 主键ID
* @return T
*/
T selectById(Serializable id); /**
* <p>
* 查询(根据ID 批量查询)
* </p>
*
* @param idList 主键ID列表
* @return List<T>
*/
List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList); /**
* <p>
* 查询(根据 columnMap 条件)
* </p>
*
* @param columnMap 表字段 map 对象
* @return List<T>
*/
List<T> selectByMap(@Param("cm") Map<String, Object> columnMap); /**
* <p>
* 根据 entity 条件,查询一条记录
* </p>
*
* @param entity 实体对象
* @return T
*/
T selectOne(@Param("ew") T entity); /**
* <p>
* 根据 Wrapper 条件,查询总记录数
* </p>
*
* @param wrapper 实体对象
* @return int
*/
Integer selectCount(@Param("ew") Wrapper<T> wrapper); /**
* <p>
* 根据 entity 条件,查询全部记录
* </p>
*
* @param wrapper 实体对象封装操作类(可以为 null)
* @return List<T>
*/
List<T> selectList(@Param("ew") Wrapper<T> wrapper); /**
* <p>
* 根据 Wrapper 条件,查询全部记录
* </p>
*
* @param wrapper 实体对象封装操作类(可以为 null)
* @return List<T>
*/
List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> wrapper); /**
* <p>
* 根据 Wrapper 条件,查询全部记录
* 注意: 只返回第一个字段的值
* </p>
*
* @param wrapper 实体对象封装操作类(可以为 null)
* @return List<Object>
*/
List<Object> selectObjs(@Param("ew") Wrapper<T> wrapper); /**
* <p>
* 根据 entity 条件,查询全部记录(并翻页)
* </p>
*
* @param rowBounds 分页查询条件(可以为 RowBounds.DEFAULT)
* @param wrapper 实体对象封装操作类(可以为 null)
* @return List<T>
*/
List<T> selectPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper); /**
* <p>
* 根据 Wrapper 条件,查询全部记录(并翻页)
* </p>
*
* @param rowBounds 分页查询条件(可以为 RowBounds.DEFAULT)
* @param wrapper 实体对象封装操作类
* @return List<Map<String, Object>>
*/
List<Map<String, Object>> selectMapsPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper); }

我们来测试它提供的CRUD(参数里带有Wrapper的先跳过,涉及条件构造器,我们之后再探讨)

为了方便查看自动生成的sql语句,我们配置log日志级别:

 logging:
level:
com:
xm:
mapper: trace

1.Select

方法名 解释
selectById() 根据主键ID查询,参数类型为:Serializable
selectOne() 根据实体里面有值的属性进行查询,参数类型为实体类型,查询结果只有一个
selectByMap() 根据map封装的字段属性进行查询,参数类型为map,结果集为List
selectBatchIds() 根据多个id生成的集合进行查询,参数类型为Connection,结果集为List

代码:

 package com.xm;

 import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import com.xm.mapper.StudentMapper;
import com.xm.pojo.Student; @RunWith(SpringRunner.class)
@SpringBootTest
public class StudentText { @Autowired
private StudentMapper studentMapper; @Test
/**
* 查询测试
*/
public void selectTest() {
/**
* selectById()
* @param Serializable id:主键ID
* sql语句:SELECT id,`name` FROM student WHERE id=?
* return: Student
*/
/*Student student = studentMapper.selectById(2);
System.out.println(student);*/ /**
* selectOne()
* @param Student entity: 学生实体
* sql语句:SELECT id,`name` FROM student WHERE `name`=?
* return: Student
*/
/*Student student = new Student();
student.setName("郭小明");
Student student2 = studentMapper.selectOne(student);
System.out.println(student2);*/ /**
* selectByMap()
* @param Map<String, Object> columnMap: 字段名为key,值为value的map
* sql语句:SELECT id,`name` FROM student WHERE name = ? AND id = ?
* return: List
*/
/*Map<String,Object> map = new HashMap<>();
map.put("name", "郭小明");
map.put("id", "2");
List<Student> students = studentMapper.selectByMap(map);
System.out.println(students);*/ /**
* selectBatchIds()
* @param Collection<? extends Serializable> idList:id组成的集合
* sql语句:SELECT id,`name` FROM student WHERE id IN ( ? , ? , ? , ? )
* return: List
*/
List<Student> stutents = studentMapper.selectBatchIds(Arrays.asList(1,2,3,4));
System.out.println(stutents);
} }

2.update

方法名 解释
updateById() 根据实体id更新实体中有值的字段,无值的属性不做修改,除id外必须含有一个属性不为null,否则执行错误
updateAllColumnById() 根据实体id更新实体中所有字段,属性为null的直接更新为null

代码:

 package com.xm;

 import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import com.xm.mapper.StudentMapper;
import com.xm.pojo.Student; @RunWith(SpringRunner.class)
@SpringBootTest
public class StudentText { @Autowired
private StudentMapper studentMapper; @Test
/**
* 更新测试
*/
public void updateTest() { /**
*updateById()
* @param Student entity:有id的学生实体
* sql语句:UPDATE student SET `name`=? WHERE id=?
* return: Integer
*/
/*Student student = new Student();
student.setId(23);
student.setName("寄生虫");
Integer num = studentMapper.updateById(student);
System.out.println("更新行数:"+num);*/ /**
*updateAllColumnById()
* @param Student entity:有id的学生实体
* sql语句:UPDATE student SET `name`=? WHERE id=?
* return: Integer
*/
Student student = new Student();
student.setId(22);
//student.setName("寄生虫");
Integer num = studentMapper.updateAllColumnById(student);
System.out.println("更新行数:"+num);
} }

3.delete

方法 解释
deleteById() 根据id进行删除
deleteBatchId() 根据id集合进行删除
deleteByMap() 根据属性名和值封装的map进行删除

代码:

 package com.xm;

 import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import com.xm.mapper.StudentMapper;
import com.xm.pojo.Student; @RunWith(SpringRunner.class)
@SpringBootTest
public class StudentText { @Autowired
private StudentMapper studentMapper; @Test
/**
* 删除测试
*/
public void deleteTest() {
/**
*deleteById()
* @param Serializable id:学生id
* sql语句:DELETE FROM student WHERE id=?
* return: Integer
*/
/*Integer num = studentMapper.deleteById(22);
System.out.println("更新行数:"+num);*/ /**
*deleteBatchId()
* @param Collection<? extends Serializable> idList:id组成的集合
* sql语句:DELETE FROM student WHERE id IN ( ? , ? , ? )
* return: Integer
*/
/*Integer num = studentMapper.deleteBatchIds(Arrays.asList(18,19,20));
System.out.println(num);*/ /**
*deleteByMap()
* @param Map<String, Object> columnMap: 字段名为key,值为value的map
* sql语句:DELETE FROM student WHERE name = ? AND id = ?
* return: Integer
*/
Map<String,Object> map = new HashMap<>();
map.put("name", "张大萨");
map.put("id", "21");
Integer num = studentMapper.deleteByMap(map);
System.out.println(num);
} }

4.insert

方法 解析
insert() 插入一个实体,必须包含至少一个属性不为null,否则添加失败
insertAllColumn() 插入一个实体,属性可以全部为空

注意:添加方法里要注意主键自动生成策略是否和数据库的一致。

原因分析:主键生成策略可能不一致
 解决策略:1.实体主键上添加注解@TableId(type=IdType.AUTO)
                   2.全局配置:
                         id-type: #主键类型  0:"数据库ID自增",
                                                        1:"用户输入ID",
                                                        2:"全局唯一ID (数字类型唯一ID)",
                                                        3:"全局唯一ID UUID";

代码:

 package com.xm;

 import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.enums.IdType;
import com.xm.mapper.StudentMapper;
import com.xm.pojo.Student; @RunWith(SpringRunner.class)
@SpringBootTest
public class StudentText { @Autowired
private StudentMapper studentMapper; @Test
/**
* 添加测试
*/
public void insertTest() { /**
* 测试失败:
* 原因分析:主键生成策略可能不一致
* 解决策略:1.实体主键上添加注解@TableId(type=IdType.AUTO)
* 2.全局配置:
* id-type: #主键类型 0:"数据库ID自增",
* 1:"用户输入ID",
* 2:"全局唯一ID (数字类型唯一ID)",
* 3:"全局唯一ID UUID";
*/ /**
*insert()
* @param Student entity:学生实体
* sql语句:INSERT INTO student ( `name` ) VALUES ( ? )
* return: Integer
*/
/*Student student = new Student();
student.setName("烤鸡翅");
Integer num = studentMapper.insert(student);
System.out.println("更新行数:"+num);*/ /**
*insertAllColumn()
* @param Student entity:学生实体
* sql语句:INSERT INTO student ( `name` ) VALUES ( ? )
* return: Integer
*/
Student student = new Student();
//student.setName("烤鸡翅");
Integer num = studentMapper.insertAllColumn(student);
System.out.println("更新行数:"+num); } }

2018-07-19

2、SpringBoot+MybatisPlus整合-------BaseCRUD的更多相关文章

  1. SpringBoot+Mybatis-Plus整合Sharding-JDBC5.1.1实现单库分表【全网最新】

    一.前言 小编最近一直在研究关于分库分表的东西,前几天docker安装了mycat实现了分库分表,但是都在说mycat的bug很多.很多人还是倾向于shardingsphere,其实他是一个全家桶,有 ...

  2. SpringBoot+MyBatisPlus整合时提示:Invalid bound statement(not found):**.dao.UserDao.queryById

    场景 在使用SpringBoot+MyBatisPlus搭建后台启动项目时,使用EasyCode自动生成代码. 在访问后台接口时提示: Invilid bound statement (not fou ...

  3. 3、SpringBoot+MybatisPlus整合-------代码生成器

    <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</art ...

  4. 1、SpringBoot+MybatisPlus整合

    <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://mave ...

  5. SpringBoot Mybatis-Plus 整合 dynamic-datasource-spring-boot-starter 对数据库进行读写分离

    准备工作 对 MySql 进行主从搭建 引入 dynamic-datasource-spring-boot-starter 坐标 引入 druid-spring-boot-starter 坐标 对应框 ...

  6. SpringBoot+Mybatis+MybatisPlus整合实现基本的CRUD操作

    SpringBoot+Mybatis+MybatisPlus整合实现基本的CRUD操作 1> 数据准备 -- 创建测试表 CREATE TABLE `tb_user` ( `id` ) NOT ...

  7. SpringBoot系列——MyBatis-Plus整合封装

    前言 MyBatis-Plus是一款MyBatis的增强工具(简称MP),为简化开发.提高效率,但我们并没有直接使用MP的CRUD接口,而是在原来的基础上封装一层通用代码,单表继承我们的通用代码,实现 ...

  8. IDEA上创建 Maven SpringBoot+mybatisplus+thymeleaf 项目

    概述 在WEB领域,Java也是在不断的探索和改进,从开始的JSP--->Struts1--->Struts2+Spring--->Spring MVC--->SpringBo ...

  9. 学习SpringBoot,整合全网各种优秀资源,SpringBoot基础,中间件,优质项目,博客资源等,仅供个人学习SpringBoot使用

    学习SpringBoot,整合全网各种优秀资源,SpringBoot基础,中间件,优质项目,博客资源等,仅供个人学习SpringBoot使用 一.SpringBoot系列教程 二.SpringBoot ...

随机推荐

  1. virtualenv(for python)

    完整: http://docs.jinkan.org/docs/flask/installation.html#installation   virtualenv 你很可能想在开发中用上 virtua ...

  2. WSGI学习系列Pecan

    Pecan Introduce Pecan是一个轻量级的基于Python的Web框架, Pecan的目标并不是要成为一个“full stack”的框架, 因此Pecan本身不支持类似Session和D ...

  3. MATLAB字符串处理

    字符串处理 MATLAB中字符串用单引号   如果字符串中存在单引号,要使用两个单引号. length()元素个数 (1)字符串的执行 格式:eval(s) s表示字符串 abs()和double() ...

  4. Linux kernel rbtree

    Linux kernel rbtree 因编写内核模块时需要用到rbtree来记录异步request,研究分析了一下kernel rbtree的使用方法,记录于此.本文主要参考了内核文档rbtree. ...

  5. 四、Oracle loop循环、while循环、for循环、if选择和case选择、更改读取数据、游标、触发器、存储过程

    数据库的设计(DataBase Design): 针对于用户特定的需求,然后我们创建出来一个最使用而且性能高的数据库! 数据库设计的步骤: 01.需求分析 02.概念结构设计 03.逻辑结构设计 04 ...

  6. 创建Brush对象

    在GDI+中,可使用笔刷,以各种个颜色和图像填充图形,GDI+的Brush类本身是一个抽象的类,所以是不能实例化Brush的 但是GDI+的API提供五个类,就扩展了Brush类并提供了具体的实现方式 ...

  7. Jquery插件之ajaxForm简介

    我们平常在使用jQuery异步提交表单的时候,一般都是加载在submit事件中,如下所示: $(document).ready(function(){ $('#myForm').submit(func ...

  8. (三)JavaScript之[事件]与[字符串]

    5].事件**JavaScript事件:HTML事件 * HTML事件是发生在HTML元素上的事情 * HTML事件可以是[浏览器的行为],也可以是[用户的行为] * * 实例: * HTML页面完成 ...

  9. Azure 7 月新公布

    Azure 7月新发布:Cosmos DB,事件中心捕捉功能,Hybrid Connections,流量管理器快速故障转移功能. 您现有的 DocumentDB 资源现已作为 Azure 门户上 Az ...

  10. 数组:获取GET的键名

    1.今天仓鼠遇到这个情况:通过$_GET获取参数,但是参数变成了键名形式 2.那仓鼠想要拿到这个键名,那就要:使用array_keys()获取数组中的所有键名,然后进行转换 代码如下: 结果: 以上 ...