• Mybatis-plus


    在有Mybatis基础的情况下,再去接触Mybatis-plus,就容易的多

    先就我现在使用情况讲讲,我眼中,它跟Mybatis啥区别吧。

    作为Mybatis的升级版,它除了具备Mybatis本身就有的功能之外,还增加了通过lambda表达式操作数据库,以及逻辑删除标识等功能

    1.引入依赖

    1. <dependency>
    2. <groupId>com.baomidougroupId>
    3. <artifactId>mybatis-plus-boot-starterartifactId>
    4. <optional>trueoptional>
    5. dependency>

    2.通过数据库中的表反向生成mapper,实体等

    2.1在idea中建立数据库连接

    2.2安装MybatisX-Generator插件

    2.3选中表,右键通过MybatisX-Generator插件去生成实体,mapper,甚至service的接口实现类都能生出来

    IDEA插件之mybatisx 插件使用教程_idea mybatis插件_IT小悟的博客-CSDN博客

    下边能看到service也能生出来,生出来的service中也自动引入了mapper 

     

    3.service调用

    3.1 生成的service长这样

    自动继承了一个ServiceImpl,这个ServiceImpl是Mybatis-Plus提供的

    1. @Service
    2. public class SysDataSourceConfigServiceImpl extends ServiceImpl
    3. implements SysDataSourceConfigService{
    4. }

    3.2 service中如何使用

    Mybatis-plus给生成的service都提供了一个公共父类,就是上边的

    ServiceImpl

    这里边有很多泛型方法,所以继承的时候指定mapper和entity之后,就可以直接调用一些现成的方法,不需要自己再去实现

    我现在一般比较常用的是

    getById(通过id查询)

    saveOrUpdate(根据id是否存在去走新增方法或者保存方法)

    updateById(但是mybatis在update的时候,不会更新空字段,如果有些情况你不希望这个字段被修改,直接在业务代码里把他置为空即可)

    我把Mybatis-plus的class文件直接贴上来了 

    1. //
    2. // Source code recreated from a .class file by IntelliJ IDEA
    3. // (powered by FernFlower decompiler)
    4. //
    5. package com.baomidou.mybatisplus.extension.service.impl;
    6. import com.baomidou.mybatisplus.core.conditions.Wrapper;
    7. import com.baomidou.mybatisplus.core.enums.SqlMethod;
    8. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    9. import com.baomidou.mybatisplus.core.metadata.TableInfo;
    10. import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
    11. import com.baomidou.mybatisplus.core.toolkit.Assert;
    12. import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
    13. import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
    14. import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
    15. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
    16. import com.baomidou.mybatisplus.extension.service.IService;
    17. import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
    18. import java.io.Serializable;
    19. import java.util.Collection;
    20. import java.util.Map;
    21. import java.util.Objects;
    22. import java.util.function.BiConsumer;
    23. import java.util.function.Consumer;
    24. import java.util.function.Function;
    25. import org.apache.ibatis.binding.MapperMethod;
    26. import org.apache.ibatis.logging.Log;
    27. import org.apache.ibatis.logging.LogFactory;
    28. import org.apache.ibatis.session.SqlSession;
    29. import org.mybatis.spring.SqlSessionUtils;
    30. import org.springframework.beans.factory.annotation.Autowired;
    31. import org.springframework.transaction.annotation.Transactional;
    32. public class ServiceImplextends BaseMapper, T> implements IService {
    33. protected Log log = LogFactory.getLog(this.getClass());
    34. @Autowired
    35. protected M baseMapper;
    36. protected Class entityClass = this.currentModelClass();
    37. protected Class mapperClass = this.currentMapperClass();
    38. public ServiceImpl() {
    39. }
    40. public M getBaseMapper() {
    41. return this.baseMapper;
    42. }
    43. public Class getEntityClass() {
    44. return this.entityClass;
    45. }
    46. /** @deprecated */
    47. @Deprecated
    48. protected boolean retBool(Integer result) {
    49. return SqlHelper.retBool(result);
    50. }
    51. protected Class currentMapperClass() {
    52. return ReflectionKit.getSuperClassGenericType(this.getClass(), ServiceImpl.class, 0);
    53. }
    54. protected Class currentModelClass() {
    55. return ReflectionKit.getSuperClassGenericType(this.getClass(), ServiceImpl.class, 1);
    56. }
    57. /** @deprecated */
    58. @Deprecated
    59. protected SqlSession sqlSessionBatch() {
    60. return SqlHelper.sqlSessionBatch(this.entityClass);
    61. }
    62. /** @deprecated */
    63. @Deprecated
    64. protected void closeSqlSession(SqlSession sqlSession) {
    65. SqlSessionUtils.closeSqlSession(sqlSession, GlobalConfigUtils.currentSessionFactory(this.entityClass));
    66. }
    67. /** @deprecated */
    68. @Deprecated
    69. protected String sqlStatement(SqlMethod sqlMethod) {
    70. return SqlHelper.table(this.entityClass).getSqlStatement(sqlMethod.getMethod());
    71. }
    72. @Transactional(
    73. rollbackFor = {Exception.class}
    74. )
    75. public boolean saveBatch(Collection entityList, int batchSize) {
    76. String sqlStatement = this.getSqlStatement(SqlMethod.INSERT_ONE);
    77. return this.executeBatch(entityList, batchSize, (sqlSession, entity) -> {
    78. sqlSession.insert(sqlStatement, entity);
    79. });
    80. }
    81. protected String getSqlStatement(SqlMethod sqlMethod) {
    82. return SqlHelper.getSqlStatement(this.mapperClass, sqlMethod);
    83. }
    84. @Transactional(
    85. rollbackFor = {Exception.class}
    86. )
    87. public boolean saveOrUpdate(T entity) {
    88. if (null == entity) {
    89. return false;
    90. } else {
    91. TableInfo tableInfo = TableInfoHelper.getTableInfo(this.entityClass);
    92. Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!", new Object[0]);
    93. String keyProperty = tableInfo.getKeyProperty();
    94. Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!", new Object[0]);
    95. Object idVal = tableInfo.getPropertyValue(entity, tableInfo.getKeyProperty());
    96. return !StringUtils.checkValNull(idVal) && !Objects.isNull(this.getById((Serializable)idVal)) ? this.updateById(entity) : this.save(entity);
    97. }
    98. }
    99. @Transactional(
    100. rollbackFor = {Exception.class}
    101. )
    102. public boolean saveOrUpdateBatch(Collection entityList, int batchSize) {
    103. TableInfo tableInfo = TableInfoHelper.getTableInfo(this.entityClass);
    104. Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!", new Object[0]);
    105. String keyProperty = tableInfo.getKeyProperty();
    106. Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!", new Object[0]);
    107. return SqlHelper.saveOrUpdateBatch(this.entityClass, this.mapperClass, this.log, entityList, batchSize, (sqlSession, entity) -> {
    108. Object idVal = tableInfo.getPropertyValue(entity, keyProperty);
    109. return StringUtils.checkValNull(idVal) || CollectionUtils.isEmpty(sqlSession.selectList(this.getSqlStatement(SqlMethod.SELECT_BY_ID), entity));
    110. }, (sqlSession, entity) -> {
    111. MapperMethod.ParamMap param = new MapperMethod.ParamMap();
    112. param.put("et", entity);
    113. sqlSession.update(this.getSqlStatement(SqlMethod.UPDATE_BY_ID), param);
    114. });
    115. }
    116. @Transactional(
    117. rollbackFor = {Exception.class}
    118. )
    119. public boolean updateBatchById(Collection entityList, int batchSize) {
    120. String sqlStatement = this.getSqlStatement(SqlMethod.UPDATE_BY_ID);
    121. return this.executeBatch(entityList, batchSize, (sqlSession, entity) -> {
    122. MapperMethod.ParamMap param = new MapperMethod.ParamMap();
    123. param.put("et", entity);
    124. sqlSession.update(sqlStatement, param);
    125. });
    126. }
    127. public T getOne(Wrapper queryWrapper, boolean throwEx) {
    128. return throwEx ? this.baseMapper.selectOne(queryWrapper) : SqlHelper.getObject(this.log, this.baseMapper.selectList(queryWrapper));
    129. }
    130. public Map getMap(Wrapper queryWrapper) {
    131. return (Map)SqlHelper.getObject(this.log, this.baseMapper.selectMaps(queryWrapper));
    132. }
    133. public V getObj(Wrapper queryWrapper, Functionsuper Object, V> mapper) {
    134. return SqlHelper.getObject(this.log, this.listObjs(queryWrapper, mapper));
    135. }
    136. /** @deprecated */
    137. @Deprecated
    138. protected boolean executeBatch(Consumer consumer) {
    139. return SqlHelper.executeBatch(this.entityClass, this.log, consumer);
    140. }
    141. protected boolean executeBatch(Collection list, int batchSize, BiConsumer consumer) {
    142. return SqlHelper.executeBatch(this.entityClass, this.log, list, batchSize, consumer);
    143. }
    144. protected boolean executeBatch(Collection list, BiConsumer consumer) {
    145. return this.executeBatch(list, 1000, consumer);
    146. }
    147. }

    上代码 

    4.Mapper使用

    4.1 生成的Mapper长这样

    1. @Mapper//这个我好像是自己加上去的
    2. public interface SysGroupMapper extends BaseMapper {
    3. }

    4.2 BaseMapper的使用 

    Mybatis-plus不光在ServiceImpl中通过泛型提供了很多基础的方法

    也在BaseMapper中通过泛型,提供了很多方法

    我一般用的比较多的

    this.baseMapper.selectBatchIds(collect);
    this.baseMapper.selectList(new LambdaQueryWrapper().in(SysGroup::getId, groupIds).select(SysGroup::getGroupName));

    直接贴上Mybatis-plus自带的BaseMapper代码

    1. //
    2. // Source code recreated from a .class file by IntelliJ IDEA
    3. // (powered by FernFlower decompiler)
    4. //
    5. package com.baomidou.mybatisplus.core.mapper;
    6. import com.baomidou.mybatisplus.core.conditions.Wrapper;
    7. import com.baomidou.mybatisplus.core.metadata.IPage;
    8. import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
    9. import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
    10. import java.io.Serializable;
    11. import java.util.Collection;
    12. import java.util.List;
    13. import java.util.Map;
    14. import org.apache.ibatis.annotations.Param;
    15. public interface BaseMapper extends Mapper {
    16. int insert(T entity);
    17. int deleteById(Serializable id);
    18. int deleteById(T entity);
    19. int deleteByMap(@Param("cm") Map columnMap);
    20. int delete(@Param("ew") Wrapper queryWrapper);
    21. int deleteBatchIds(@Param("coll") Collection idList);
    22. int updateById(@Param("et") T entity);
    23. int update(@Param("et") T entity, @Param("ew") Wrapper updateWrapper);
    24. T selectById(Serializable id);
    25. List selectBatchIds(@Param("coll") Collection idList);
    26. List selectByMap(@Param("cm") Map columnMap);
    27. default T selectOne(@Param("ew") Wrapper queryWrapper) {
    28. List ts = this.selectList(queryWrapper);
    29. if (CollectionUtils.isNotEmpty(ts)) {
    30. if (ts.size() != 1) {
    31. throw ExceptionUtils.mpe("One record is expected, but the query result is multiple records", new Object[0]);
    32. } else {
    33. return ts.get(0);
    34. }
    35. } else {
    36. return null;
    37. }
    38. }
    39. Long selectCount(@Param("ew") Wrapper queryWrapper);
    40. List selectList(@Param("ew") Wrapper queryWrapper);
    41. List> selectMaps(@Param("ew") Wrapper queryWrapper);
    42. List selectObjs(@Param("ew") Wrapper queryWrapper);
    43. extends IPage> P selectPage(P page, @Param("ew") Wrapper queryWrapper);

    44. extends IPage>> P selectMapsPage(P page, @Param("ew") Wrapper queryWrapper);

    45. }
    46. 贴一段代码 

       

      4.3正常使用mapper

      5.lambda表达式

      1. List sysGroups = this.baseMapper.selectList(new LambdaQueryWrapper().in(SysGroup::getId, groupIds).select(SysGroup::getGroupName));
      2. sysUserGroupMapper.delete(new LambdaQueryWrapper().eq(SysUserGroup::getUserName,username));
      3. List list = sysUserService.list(new LambdaQueryWrapper().in(SysUser::getId, userIdList).select(SysUser::getUsername));
      4. List list = this.list(new LambdaQueryWrapper().ne(id != null, SysGroup::getId, id).eq(SysGroup::getGroupName, groupName));
      5. boolean result = this.update(new LambdaUpdateWrapper()
      6. .eq(SysMenu::getId, menuId)
      7. .set(SysMenu::getVisible, status)
      8. );

      6.实体注解

    47. 相关阅读:
      前端(五)
      多路复用补充
      HTML属性,标签
      Win10笔记本开热点后电脑断网的解决方法
      基于SpringBoot的精准扶贫管理系统
      Linux项目实训一
      【MySQL】约束
      使用 DCGAN 生成动漫面孔-附训练数据集下载
      上传文件夹里面的文件后,按树结构的table表格展示
      【JavaSE专栏90】用最简单的方法,使用 JDBC 连接 MySQL 数据库
    48. 原文地址:https://blog.csdn.net/qq_35653822/article/details/133817207