Mybatis-plus常用方法总结
定义DO对象
@TableName(value ="menu")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MenuEntity implements Serializable {
/**
* 菜单ID
*/
@TableId(type = IdType.AUTO)
private Integer menuId;
/**
* 菜单名称
*/
private String name;
/**
* 父菜单ID
*/
private Integer parentId;
/**
*创建时间
*/
@JsonFormat(pattern = "yyyy/MM/dd HH:mm",timezone = "GMT+8")
private Date createdTime;
/**
* 创建者
*/
private String createdBy;
/**
* 修改时间
*/
@JsonFormat(pattern = "yyyy/MM/dd HH:mm",timezone = "GMT+8")
private Date updatedTime;
/**
* 修改用户
*/
private String updatedBy;
mapper
@Mapper
public interface MenuMapper extends BaseMapper<MenuEntity> {}
Service
public interface MenuService extends IService<MenuEntity> {
}
查询常用方法
//通过eq获取parentId==0的所有menu-->list()
List<MenuEntity> list = new LambdaQueryChainWrapper<MenuEntity>(menuMapper)
.eq(MenuEntity::getParentId, 0)
.list();
//获取menuId为指定值的一个menu对象-->one()
MenuEntity entity = new LambdaQueryChainWrapper<MenuEntity>(menuMapper)
.eq(MenuEntity::getMenuId, menuId)
.one();
在使用LambdaQueryChainWrapper时可以使用多种条件查询
eq --> equal等于
ne–> not equal不等于
gt --> greater than大于
lt --> less than小于
ge --> greater than or equal 大于等于
le --> less than or equal 小于等于
in --> in 包含(数组)
isNull --> 等于null
between --> 在2个条件之间(包括边界值)
like–>%XX%、likeLeft–>%XX、likeRight–>XX%
orderByDesc–>降序、orderByAsc–>升序
以此来构造查询条件获取所需要的值(附上一张图)
分页查询-mybatisPlus
常用的查询自然还有分页查询,以下时最近使用MybatisPlus写的一个分页查询的案例
首先做一个分页配置,用于处理分页
@Configuration
public class MybatisPlusConfiguration {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// select database
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
Page<SysRoles> rolesPage = new Page<>(pageCurrent, pageSize);
LambdaQueryWrapper<SysRoles> queryWrapper = new LambdaQueryWrapper<>();
if (DataUtils.isEmpty(role)) {
Page<SysRoles> sysRolesPage = sysRolesDao.selectPage(rolesPage, queryWrapper);
if (sysRolesPage == null) {
throw new ServiceException("未查询到相关数据");
}
return new PaginationData<SysRoles>(sysRolesPage.getRecords(), new Pagination(sysRolesPage));
}
if (DataUtils.isNotEmpty(role.getId())) {
queryWrapper.eq(SysRoles::getId, role.getId());
} else if (DataUtils.isNotEmpty(role.getName())) {
queryWrapper.like(SysRoles::getName, "%" + role.getName() + "%");
} else if (DataUtils.isNotEmpty(role.getNote())) {
queryWrapper.like(SysRoles::getNote, "%" + role.getNote() + "%");
} else if (DataUtils.isNotEmpty(role.getOperateBy())) {
queryWrapper.like(SysRoles::getCreateduser, "%" + role.getOperateBy() + "%")
.or()
.like(SysRoles::getModifieduser, "%" + role.getOperateBy() + "%");
}
Page<SysRoles> pagination = sysRolesDao.selectPage(rolesPage, queryWrapper);
List<SysRoles> roleList = pagination.getRecords();
主要是时使用mybatisPlus的一个mapper类自带的一个selectPage()方法获取到一个page对象
public class Page<T> implements IPage<T> {
private static final long serialVersionUID = 8545996863226528798L;
protected List<T> records;
protected long total;
protected long size;
protected long current;
protected List<OrderItem> orders;
protected boolean optimizeCountSql;
protected boolean isSearchCount;
protected boolean hitCount;
protected String countId;
protected Long maxLimit;
page对象主要时获取了以上的一些属性
一般需要前端都需要获取到以上的total , record ,size …的一些属性
删除方法
LambdaQueryWrapper<DeviceEntity> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(DeviceEntity::getDeviceSn, deviceSn);
mapper.delete(wrapper);
主要是使用mybatisPlus自带mapper的一个delete方法,结合LambdaQueryWrapper做一些条件筛选
public interface BaseMapper<T> extends Mapper<T> {
int insert(T entity);
int deleteById(Serializable id);
int deleteByMap(@Param("cm") Map<String, Object> columnMap);
int delete(@Param("ew") Wrapper<T> queryWrapper);
int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);
int updateById(@Param("et") T entity);
int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);
T selectById(Serializable id);
List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
T selectOne(@Param("ew") Wrapper<T> queryWrapper);
Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);
List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);
List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);
<E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper);
<E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper);
}
可以看到baseMapper中的一些方法,能够提供给我们使用。
int deleteByMap(@Param("cm") Map<String, Object> columnMap);
int delete(@Param("ew") Wrapper<T> queryWrapper);
int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);
都能够来满足我们对删除操作的需求,包括批量的删除操作
修改操作
仍然以我最近使用mp写的一个修改操作为例
LambdaUpdateChainWrapper<DeviceEntity> wrapper = new LambdaUpdateChainWrapper<>(mapper)
.eq(DeviceEntity::getDeviceSn, sn);
if (DataUtils.isEmpty(deviceNickNameIpDTO.getNickName()) && DataUtils.isEmpty(deviceNickNameIpDTO.getIp())){
throw new ServiceException("The deviceNickNameIpDTO is empty");
}
if (DataUtils.isNotEmpty(deviceNickNameIpDTO.getNickName())){
wrapper.set(DeviceEntity::getNickname, deviceNickNameIpDTO.getNickName());
}
if (DataUtils.isNotEmpty(deviceNickNameIpDTO.getIp())){
wrapper.set(DeviceEntity::getIp, deviceNickNameIpDTO.getIp());
}
boolean update = wrapper.update();
LambdaUpdateChainWrapper提供了我们对修改的操作,使用eq指定一个修改对象,再使用set()进行修改,最后调用update()
可以看到update()也可以让我们主动传入一个DO对象进行对应修改
添加操作(批量+单个)
public interface BaseMapper<T> extends Mapper<T> {
int insert(T entity);
插入操作主要也是调用实现baseMapper的mapper调用update()做一个插入的实现
然而 BaseMapper
中不提供批量插入方法,只有单条插入方式。那如何批量插入呢?
但是在业务中我可能会用到批量插入的一个功能实现
mybatis-plus 中提供了BaseMapper的子类 ServiceImpl
里有实现批量插入方法
ServiceImpl<M extends BaseMapper<T>, T>
是 Mybatis-Plus 提供的 Service 接口的默认实现类,它实现了 IService<T>
接口,提供了一些通用的方法,包括增删改查、批量操作等
<M extends BaseMapper<T>, T>
:M 代表 Mapper 接口,T 代表实体类。这里声明了两个泛型参数,一个是 M,表示该 Service 中使用的 Mapper 接口;另一个是 T,表示该 Service 中操作的实体类对象类型。由于该类是一个抽象类,因此需要通过子类来指定具体的实体类和 Mapper 接口。extends BaseMapper<T>
:这里的BaseMapper<T>
是 Mybatis-Plus 提供的 Mapper 接口,它包含了一些基本的 CRUD 操作方法,例如 insert、update、delete 和 select 等。ServiceImpl
类继承了BaseMapper<T>
接口,从而获得了这些基本的操作方法,可以在其基础上扩展更多的业务方法。
public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T>{
@Override
public boolean insertBatch(List<T> entityList) {
return insertBatch(entityList, 30);
}
/**
* 批量插入
*
* @param entityList
* @param batchSize
* @return
*/
@Transactional(rollbackFor = Exception.class)
@Override
public boolean insertBatch(List<T> entityList, int batchSize) {
if (CollectionUtils.isEmpty(entityList)) {
throw new IllegalArgumentException("Error: entityList must not be empty");
}
try (SqlSession batchSqlSession = sqlSessionBatch()) {
int size = entityList.size();
String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE);
for (int i = 0; i < size; i++) {
batchSqlSession.insert(sqlStatement, entityList.get(i));
if (i >= 1 && i % batchSize == 0) {
batchSqlSession.flushStatements();
}
}
batchSqlSession.flushStatements();
} catch (Throwable e) {
throw new MybatisPlusException("Error: Cannot execute insertBatch Method. Cause", e);
}
return true;
}
}
① 增加实现类
@Service
public class ShopCityWapperImpl extends ServiceImpl<TerminalShopCityMapper, TerminalShopCityInfo> {
}
ShopCityWapperImpl
此时就有insertBatch()提供批量的插入
当然在mybatisPlus中我们也可以使用mapper文件
来写一些我们所需要的SQL语句。包括我们的批量插入
<insert id="batchInsert" parameterType="java.util.List">
insert into user (id, name, age)
values
<foreach collection="list" item="item" separator=",">
(#{item.id}, #{item.name}, #{item.age})
</foreach>
</insert>
文章均为个人工作中的一些小总结,如果有错误欢迎各位大佬评论指出,一起进步