io.github.dengchen2020.mybatis.base.BaseMybatisRepository Maven / Gradle / Ivy
package io.github.dengchen2020.mybatis.base;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import io.github.dengchen2020.core.support.model.PageParam;
import io.github.dengchen2020.core.utils.SqlMetaUtils;
import org.apache.commons.collections4.IterableUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.GenericTypeResolver;
import org.springframework.lang.NonNull;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
/**
* Mybatis-Repository基类接口
*
* @author dengchen
* @since 2024/6/22
*/
public interface BaseMybatisRepository extends ComplexMybatisRepository {
Logger log = LoggerFactory.getLogger(BaseMybatisRepository.class);
/**
* 软删除- 支持批量 set deleted = 1
*
* @param ids id集合
* @return 受影响的行数
*/
int softDelete(Collection ids);
/**
* 软删除- 支持批量 set deleted = 1
*
* @param id id
* @return 受影响的行数
*/
default int softDelete(String id) {
return softDelete(List.of(id));
}
/**
* 删除-支持批量
*
* @param ids id集合
* @return 受影响的行数
*/
default int delete(Collection ids) {
return deleteByIds(IterableUtils.toList(ids));
}
/**
* 删除
*
* @param id id
* @return 受影响的行数
*/
default int delete(String id) {
return deleteById(id);
}
/**
* selectById 加锁版本
*
* @param id id
* @return T
*/
@Transactional
T selectByIdForUpdate(String id);
/**
* findById 加锁版本
*
* @param id id
* @return Optional
*/
@Transactional
default Optional findByIdForUpdate(String id) {
return Optional.ofNullable(selectByIdForUpdate(id));
}
/**
* 根据id查询
*
* @param id id
* @return Optional
*/
@NonNull
default Optional findById(@NonNull String id) {
return Optional.ofNullable(selectById(id));
}
/**
* 根据id集合查询
*
* @param ids id集合
* @return List
*/
default List selectInIds(Collection ids) {
return selectBatchIds(IterableUtils.toList(ids));
}
default T save(T entity) {
SqlMetaUtils.init(entity.getClass());
if (SqlMetaUtils.isNew(entity)) {
SqlMetaUtils.onBeforeConvert(entity);
insert(entity);
SqlMetaUtils.onAfterConvert(entity);
} else {
SqlMetaUtils.onBeforeConvert(entity);
updateById(entity);
SqlMetaUtils.onAfterConvert(entity);
}
return entity;
}
default Iterable saveAll(Collection entities) {
entities.forEach(this::save);
return entities;
}
default Iterable saveAllFast(Collection entities) {
Class> entityClass = GenericTypeResolver.resolveTypeArgument(this.getClass(),
BaseMapper.class);
if (entityClass == null){
log.error("批量保存异常警告,获取批量保存的实体类型失败:{}",entities);
return entities;
}
List insertList = new ArrayList<>();
List updateList = new ArrayList<>();
SqlMetaUtils.init(entityClass);
entities.forEach(entity -> {
if (SqlMetaUtils.isNew(entity)) {
SqlMetaUtils.onBeforeConvert(entity);
insertList.add(entity);
} else {
SqlMetaUtils.onBeforeConvert(entity);
updateList.add(entity);
}
});
insert(insertList);
updateById(updateList);
return entities;
}
}