import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;
public class BaseServiceImpl implements BaseService {
//继承通用service的类都要添加Mapper
@Autowired
protected XxxMapper xxxMapper;
protected BaseMapper<T> baseMapper;
@PostConstruct//在构造方法后,初化前执行
private void initBaseMapper() throws Exception{
//完成以下逻辑,需要对研发本身进行命名与使用规范
//this关键字指对象本身,这里指的是调用此方法的实现类(子类)
ParameterizedType type =(ParameterizedType) this.getClass().getGenericSuperclass();
//获取第一个参数的class
@SuppressWarnings("rawtypes")
Class clazz = (Class)type.getActualTypeArguments()[0];
//转化为属性名(相关的Mapper子类的引用名)Supplier supplierMapper
String localField = clazz.getSimpleName().substring(0,1).toLowerCase()+clazz.getSimpleName().substring(1)+"Mapper";
//getDeclaredField:可以使用于包括私有、默认、受保护、公共字段,但不包括继承的字段
Field field=this.getClass().getSuperclass().getDeclaredField(localField);
Field baseField = this.getClass().getSuperclass().getDeclaredField("baseMapper");
//field.get(this)获取当前this的field字段的值。例如:Supplier对象中,baseMapper所指向的对象为其子类型SupplierMapper对象,子类型对象已被spring实例化于容器中
baseField.set(this, field.get(this));
}
@Override
public void insert(T entity) {
baseMapper.insert(entity);
}
@Override
public void update(T entity) {
baseMapper.update(entity);
}
@Override
public void delete(Serializable id) {
baseMapper.delete(id);
}
@Override
public T findObjectById(Serializable id) {
return baseMapper.findObjectById(id);
}
@Override
public List<T> findObjects() {
return baseMapper.findObjects();
}
//分页查询
@Override
public PageNation doPageNation(Map<String, Object> paraMap) {
int pageNo; //当前页号
int pageSize; //每页大小
int currLine; //当前行号
long totalCount; //总记录数
//如果没有传入当前页号,默认为1
if (paraMap.get("pageNo") == null){
pageNo = 1;
} else {
pageNo = (int) paraMap.get("pageNo");
}
//如果没有传入每页大小,默认为2
if (paraMap.get("pageSize") == null){
pageSize = 2;
} else {
pageSize = (int) paraMap.get("pageSize");
}
//计算当前行号
currLine = (pageNo - 1) * pageSize;
paraMap.put("currLine", currLine);
paraMap.put("pageSize", pageSize);
totalCount = baseMapper.findPageCount(paraMap);
//查询列表(无条件/有条件)
List<T> items= baseMapper.findPageList(paraMap);
//本页列表删除,返回上一页
if(totalCount > 0 && items.size() == 0 && pageNo > 1){
pageNo = pageNo - 1;
currLine = (pageNo - 1) * pageSize;
paraMap.put("currLine", currLine);
items = baseMapper.findPageList(paraMap);
}
return new PageNation(totalCount, pageNo, items, pageSize);
}
}