MyBatis-Spring-Boot
MyBatis-Spring-Boot copied to clipboard
如果实现了 通用的 Service 会出现 同时找到多个 mapper
No qualifying bean of type 'tk.mybatis.mapper.common.Mapper<?>' available: expected single matching bean but found 3
异常如上。 通用Service 如下: @Service public abstract class AbsBaseService<T> implements BaseService<T> {
@Resource
protected Mapper<T> mapper;
//根据id查询实体
public T queryById(String id){
return this.mapper.selectByPrimaryKey(id);
}
//查询所有
public List<T> queryAll(){
return this.mapper.select(null);
}
//条件查询
public List<T> queryListByWhere(T param){
return this.mapper.select(param);
}
//查询记录数
public Integer queryCount(T param){
return this.mapper.selectCount(param);
}
//分页
public PageInfo<T> queryListByWhere(T param, Integer page, Integer rows){
PageHelper.startPage(page, rows);
List<T> list = this.queryListByWhere(param);
return new PageInfo<>(list);
}
//查询一条记录
public T queryOne(T param){
return this.mapper.selectOne(param);
}
//插入
public Integer save(T param){
return this.mapper.insert(param);
}
//新增非空字段
public Integer saveSelect(T param){
return this.mapper.insertSelective(param);
}
//根据主键更新
public Integer update(T param){
return this.mapper.updateByPrimaryKey(param);
}
//根据主键更新非空字段
public Integer updateSelective(T param){
return this.mapper.updateByPrimaryKeySelective(param);
}
//根据主键删除
public Integer deleteById(String id){
return this.mapper.deleteByPrimaryKey(id);
}
//批量删除
public Integer deleteByIds(Class<T> clazz,List<Object> values){
Example example = new Example(clazz);
example.createCriteria().andIn("id", values);
return this.mapper.deleteByExample(example);
}
}
解决办法: 通用的Service: public abstract class AbsBaseService<T> implements BaseService<T> {
private Mapper<T> mapper;
public void setMapper(Mapper<T> mapper) {
this.mapper= mapper;
}
实现的Service: @Resource private UsersMapper usersMapper;
@Autowired
public void setUsersMapper(){
super.setMapper(usersMapper);
}
不必这样,出错的原因是你注解用错了。
泛型注入时,必须使用 @Autowired。
直接:
@Service
public abstract class AbsBaseService implements BaseService {
@Autowired
protected Mapper<T> mapper;
@abel533 按照你这样写的,还是报以下错误: Field mapper in com.didi.commons.utils.BaseService required a bean of type 'tk.mybatis.mapper.common.Mapper' that could not be found.
@Service public abstract class BaseService<T, ID> {
@Autowired
private Mapper<T> mapper;
参考guozilanTK: https://github.com/guozilanTK/base/blob/master/base-service/src/main/java/tk/guozilan/base/service/AbstractService.java
@Jacob-W 请问“Field mapper in com.didi.commons.utils.BaseService required a bean of type 'tk.mybatis.mapper.common.Mapper' that could not be found.”您的这个问题解决了吗? 求教,谢谢!