SpringBoot+Mybatis-plus写数据库的函数调用过程
比如我们SpringBoot的一个接口层为DataCollectController,它通过调用服务层DataCollectManager的create()和update()方法对数据库进行写操作
@RestController
@Api(tags="数据采集")
@RequestMapping("/dataCollect/")
@ApiGroup(group= {ApiGroupInner.GROUP_TEMPLATE})
public class DataCollectController extends BaseController<DataCollectManager, DataCollect> {
@Resource
DataCollectManager dataCollectManager;
@Autowired//使用@Autowired将另一个Controller类的实例注入进来,并直接调用该实例的方法
DataSourceController dataSourceController;
@RequestMapping(value="start", method= RequestMethod.POST, produces = { "application/json; charset=utf-8" })
@ApiOperation(value = "开始数据库采集", httpMethod = "POST", notes = "开始数据库采集")
public CommonResult<String> StartDataCollect(
@ApiParam(name="dataCollect", value="数据采集对象", required = true)
@RequestBody DataCollect dataCollect) throws Exception{
if (StringUtil.isEmpty(dataCollect.getId())) {//如果请求中不填id
//将参数存入数据库data_collect
dataCollectManager.create(dataCollect);
}
else {
dataCollectManager.update(dataCollect);
}
...
}
}
DataCollectManager的实现类DataCollectManagerImpl继承了BaseManagerImpl的create和update方法
@Service
public class DataCollectManagerImpl extends BaseManagerImpl<DataCollectDao, DataCollect> implements DataCollectManager {
protected static final Logger LOGGER = LoggerFactory.getLogger(DataCollectManagerImpl.class);
@Override
public void create(DataCollect dataCollect) {
super.create(dataCollect);//调用BaseManagerImpl.create
}
@Override
public void update(DataCollect dataCollect) {
super.update(dataCollect);
}
}
BaseManagerImpl的create和update方法则继承自ServiceImpl的save和updateById,从这里开始就是Mybatis-plus的代码了
public class BaseManagerImpl<M extends BaseMapper<T>, T extends Model<T>> extends ServiceImpl<M, T> implements BaseManager<T>, QueryFilterHelper<T> {
public BaseManagerImpl() {
}
public T get(Serializable id) {
return (Model)this.getById(id);
}
public void create(T t) {
this.save(t);
}
public void update(T t) {
this.updateById(t);
}
...
}
ServiceImpl继承自IService,可以看到save操作调用了getBaseMapper(),该函数会自动关联DataCollectMapper.xml文件,在调用insert()时自动生成写数据库的SQL语句并执行。
public interface IService<T> {
/**
* 默认批次提交数量
*/
int DEFAULT_BATCH_SIZE = 1000;
/**
* 插入一条记录(选择字段,策略插入)
*
* @param entity 实体对象
*/
default boolean save(T entity) {
return SqlHelper.retBool(getBaseMapper().insert(entity));
}