下载的尚硅谷的视频是 2.3 版本,比较低了。
目前官网最新版本是:3.1.2.2。
如下 BaseMapper 和 ServiceImpl 源码:
/*
* Copyright (c) 2011-2020, baomidou ([email protected]).
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* 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.core.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.ibatis.annotations.Param;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/*
:`
.:,
:::,,.
:: `::::::
::` `,:,` .:`
`:: `::::::::.:` `:';,`
::::, .:::` `@++++++++:
`` :::` @+++++++++++#
:::, #++++++++++++++`
,: `::::::;'##++++++++++
.@#@;` ::::::::::::::::::::;
#@####@, :::::::::::::::+#;::.
@@######+@:::::::::::::. #@:;
, @@########':::::::::::: .#''':`
;##@@@+:##########@::::::::::: @#;.,:.
#@@@######++++#####'::::::::: .##+,:#`
@@@@@#####+++++'#####+::::::::` ,`::@#:`
`@@@@#####++++++'#####+#':::::::::::@.
@@@@######+++++''#######+##';::::;':,`
@@@@#####+++++'''#######++++++++++`
#@@#####++++++''########++++++++'
`#@######+++++''+########+++++++;
`@@#####+++++''##########++++++,
@@######+++++'##########+++++#`
@@@@#####+++++############++++;
;#@@@@@####++++##############+++,
@@@@@@@@@@@###@###############++'
@#@@@@@@@@@@@@###################+:
`@#@@@@@@@@@@@@@@###################'`
:@#@@@@@@@@@@@@@@@@@##################,
,@@@@@@@@@@@@@@@@@@@@################;
,#@@@@@@@@@@@@@@@@@@@##############+`
.#@@@@@@@@@@@@@@@@@@#############@,
@@@@@@@@@@@@@@@@@@@###########@,
:#@@@@@@@@@@@@@@@@##########@,
`##@@@@@@@@@@@@@@@########+,
`+@@@@@@@@@@@@@@@#####@:`
`:@@@@@@@@@@@@@@##@;.
`,'@@@@##@@@+;,`
``...``
_ _ /_ _ _/_. ____ / _
/ / //_//_//_|/ /_\ /_///_/_\ Talk is cheap. Show me the code.
_/ /
*/
/**
* Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
*
这个 Mapper 支持 id 泛型
*
* @author hubin
* @since 2016-01-23
*/
public interface BaseMapper extends Mapper {
/**
* 插入一条记录
*
* @param entity 实体对象
*/
int insert(T entity);
/**
* 根据 ID 删除
*
* @param id 主键ID
*/
int deleteById(Serializable id);
/**
* 根据 columnMap 条件,删除记录
*
* @param columnMap 表字段 map 对象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map columnMap);
/**
* 根据 entity 条件,删除记录
*
* @param wrapper 实体对象封装操作类(可以为 null)
*/
int delete(@Param(Constants.WRAPPER) Wrapper wrapper);
/**
* 删除(根据ID 批量删除)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection extends Serializable> idList);
/**
* 根据 ID 修改
*
* @param entity 实体对象
*/
int updateById(@Param(Constants.ENTITY) T entity);
/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper updateWrapper);
/**
* 根据 ID 查询
*
* @param id 主键ID
*/
T selectById(Serializable id);
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List selectBatchIds(@Param(Constants.COLLECTION) Collection extends Serializable> idList);
/**
* 查询(根据 columnMap 条件)
*
* @param columnMap 表字段 map 对象
*/
List selectByMap(@Param(Constants.COLUMN_MAP) Map columnMap);
/**
* 根据 entity 条件,查询一条记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
T selectOne(@Param(Constants.WRAPPER) Wrapper queryWrapper);
/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper queryWrapper);
/**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List selectList(@Param(Constants.WRAPPER) Wrapper queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List
/*
* Copyright (c) 2011-2020, baomidou ([email protected]).
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* 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.extension.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* IService 实现类( 泛型:M 是 mapper 对象,T 是实体 , PK 是主键泛型 )
*
* @author hubin
* @since 2018-06-23
*/
@SuppressWarnings("unchecked")
public class ServiceImpl, T> implements IService {
protected Log log = LogFactory.getLog(getClass());
@Autowired
protected M baseMapper;
@Override
public M getBaseMapper() {
return baseMapper;
}
/**
* 判断数据库操作是否成功
*
* @param result 数据库操作返回影响条数
* @return boolean
*/
protected boolean retBool(Integer result) {
return SqlHelper.retBool(result);
}
protected Class currentModelClass() {
return (Class) ReflectionKit.getSuperClassGenericType(getClass(), 1);
}
/**
* 批量操作 SqlSession
*/
protected SqlSession sqlSessionBatch() {
return SqlHelper.sqlSessionBatch(currentModelClass());
}
/**
* 释放sqlSession
*
* @param sqlSession session
*/
protected void closeSqlSession(SqlSession sqlSession) {
SqlSessionUtils.closeSqlSession(sqlSession, GlobalConfigUtils.currentSessionFactory(currentModelClass()));
}
/**
* 获取 SqlStatement
*
* @param sqlMethod ignore
* @return ignore
*/
protected String sqlStatement(SqlMethod sqlMethod) {
return SqlHelper.table(currentModelClass()).getSqlStatement(sqlMethod.getMethod());
}
@Override
public boolean save(T entity) {
return retBool(baseMapper.insert(entity));
}
/**
* 批量插入
*
* @param entityList ignore
* @param batchSize ignore
* @return ignore
*/
@Transactional(rollbackFor = Exception.class)
@Override
public boolean saveBatch(Collection entityList, int batchSize) {
String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE);
try (SqlSession batchSqlSession = sqlSessionBatch()) {
int i = 0;
for (T anEntityList : entityList) {
batchSqlSession.insert(sqlStatement, anEntityList);
if (i >= 1 && i % batchSize == 0) {
batchSqlSession.flushStatements();
}
i++;
}
batchSqlSession.flushStatements();
}
return true;
}
/**
* TableId 注解存在更新记录,否插入一条记录
*
* @param entity 实体对象
* @return boolean
*/
@Transactional(rollbackFor = Exception.class)
@Override
public boolean saveOrUpdate(T entity) {
if (null != entity) {
Class> cls = entity.getClass();
TableInfo tableInfo = TableInfoHelper.getTableInfo(cls);
Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
String keyProperty = tableInfo.getKeyProperty();
Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!");
Object idVal = ReflectionKit.getMethodValue(cls, entity, tableInfo.getKeyProperty());
return StringUtils.checkValNull(idVal) || Objects.isNull(getById((Serializable) idVal)) ? save(entity) : updateById(entity);
}
return false;
}
@Transactional(rollbackFor = Exception.class)
@Override
public boolean saveOrUpdateBatch(Collection entityList, int batchSize) {
Assert.notEmpty(entityList, "error: entityList must not be empty");
Class> cls = currentModelClass();
TableInfo tableInfo = TableInfoHelper.getTableInfo(cls);
Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
String keyProperty = tableInfo.getKeyProperty();
Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!");
try (SqlSession batchSqlSession = sqlSessionBatch()) {
int i = 0;
for (T entity : entityList) {
Object idVal = ReflectionKit.getMethodValue(cls, entity, keyProperty);
if (StringUtils.checkValNull(idVal) || Objects.isNull(getById((Serializable) idVal))) {
batchSqlSession.insert(sqlStatement(SqlMethod.INSERT_ONE), entity);
} else {
MapperMethod.ParamMap param = new MapperMethod.ParamMap<>();
param.put(Constants.ENTITY, entity);
batchSqlSession.update(sqlStatement(SqlMethod.UPDATE_BY_ID), param);
}
// 不知道以后会不会有人说更新失败了还要执行插入 ???
if (i >= 1 && i % batchSize == 0) {
batchSqlSession.flushStatements();
}
i++;
}
batchSqlSession.flushStatements();
}
return true;
}
@Override
public boolean removeById(Serializable id) {
return SqlHelper.retBool(baseMapper.deleteById(id));
}
@Override
public boolean removeByMap(Map columnMap) {
Assert.notEmpty(columnMap, "error: columnMap must not be empty");
return SqlHelper.retBool(baseMapper.deleteByMap(columnMap));
}
@Override
public boolean remove(Wrapper wrapper) {
return SqlHelper.retBool(baseMapper.delete(wrapper));
}
@Override
public boolean removeByIds(Collection extends Serializable> idList) {
return SqlHelper.retBool(baseMapper.deleteBatchIds(idList));
}
@Override
public boolean updateById(T entity) {
return retBool(baseMapper.updateById(entity));
}
@Override
public boolean update(T entity, Wrapper updateWrapper) {
return retBool(baseMapper.update(entity, updateWrapper));
}
@Transactional(rollbackFor = Exception.class)
@Override
public boolean updateBatchById(Collection entityList, int batchSize) {
Assert.notEmpty(entityList, "error: entityList must not be empty");
String sqlStatement = sqlStatement(SqlMethod.UPDATE_BY_ID);
try (SqlSession batchSqlSession = sqlSessionBatch()) {
int i = 0;
for (T anEntityList : entityList) {
MapperMethod.ParamMap param = new MapperMethod.ParamMap<>();
param.put(Constants.ENTITY, anEntityList);
batchSqlSession.update(sqlStatement, param);
if (i >= 1 && i % batchSize == 0) {
batchSqlSession.flushStatements();
}
i++;
}
batchSqlSession.flushStatements();
}
return true;
}
@Override
public T getById(Serializable id) {
return baseMapper.selectById(id);
}
@Override
public Collection listByIds(Collection extends Serializable> idList) {
return baseMapper.selectBatchIds(idList);
}
@Override
public Collection listByMap(Map columnMap) {
return baseMapper.selectByMap(columnMap);
}
@Override
public T getOne(Wrapper queryWrapper, boolean throwEx) {
if (throwEx) {
return baseMapper.selectOne(queryWrapper);
}
return SqlHelper.getObject(log, baseMapper.selectList(queryWrapper));
}
@Override
public Map getMap(Wrapper queryWrapper) {
return SqlHelper.getObject(log, baseMapper.selectMaps(queryWrapper));
}
@Override
public int count(Wrapper queryWrapper) {
return SqlHelper.retCount(baseMapper.selectCount(queryWrapper));
}
@Override
public List list(Wrapper queryWrapper) {
return baseMapper.selectList(queryWrapper);
}
@Override
public IPage page(IPage page, Wrapper queryWrapper) {
return baseMapper.selectPage(page, queryWrapper);
}
@Override
public List
这两个关键类会对业务 sql 进行拼接。