im.shs.tick.mybatis.service.impl.BaseService Maven / Gradle / Ivy
The newest version!
package im.shs.tick.mybatis.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import im.shs.tick.mybatis.injector.CustomSqlMethod;
import im.shs.tick.mybatis.service.IBaseService;
import im.shs.tick.mybatis.mapper.BaseMapper;
import org.apache.ibatis.session.SqlSession;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
/**
* BaseService 实现类( 泛型:M 是 mapper 对象,T 是实体 , PK 是主键泛型 )
*
* @author SimpleJuly
*/
public class BaseService, T> extends ServiceImpl implements IBaseService {
@Override
public boolean saveIgnore(T entity) {
return retBool(baseMapper.insertIgnore(entity));
}
@Override
public boolean saveReplace(T entity) {
return retBool(baseMapper.replace(entity));
}
@Transactional(rollbackFor = Exception.class)
@Override
public boolean saveIgnoreBatch(Collection entityList, int batchSize) {
return saveBatch(entityList, batchSize, CustomSqlMethod.INSERT_IGNORE_ONE);
}
@Transactional(rollbackFor = Exception.class)
@Override
public boolean saveReplaceBatch(Collection entityList, int batchSize) {
return saveBatch(entityList, batchSize, CustomSqlMethod.REPLACE_ONE);
}
private boolean saveBatch(Collection entityList, int batchSize, CustomSqlMethod sqlMethod) {
String sqlStatement = mySqlStatement(sqlMethod);
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;
}
/**
* 获取SqlStatement
*
* @param sqlMethod ignore
* @return sql
*/
protected String mySqlStatement(CustomSqlMethod sqlMethod) {
return SqlHelper.table(currentModelClass()).getSqlStatement(sqlMethod.getMethod());
}
}