实体类等不赘述。
1.新建一个BaseMapper文件,继承几种基础mapper,可根据需求自行添加
public interface MyMapper<T>
extends BaseMapper<T>,
ConditionMapper<T>,
IdsMapper<T>,
ExampleMapper<T>,
InsertListMapper<T>,
MySqlMapper<T> {
}
2.新建一个BaseService,此处仅添加根据condition查找的方法,可自行添加其他需要使用的一些方法。
public interface MyBaseService<T> {
void deleteByCondition(T model, Condition condition);
List<T> findByCondition(Condition condition);
}
3.实现BaseService
public abstract class AbstractServiceImpl<T> implements MyService<T> {
@Autowired
protected MyMapper<T> mapper;
private Class<T> modelClass;
public AbstractServiceImpl() {
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
modelClass = (Class<T>) pt.getActualTypeArguments()[0];
}
public void deleteByCondition(T model, Condition condition) {
mapper.updateByConditionSelective(model,condition);
}
public List<T> findByCondition(Condition condition) {
return mapper.selectByCondition(condition);
}
}
4.在方法实现类下引用
接口定义
public interface StudentService extends MyBaseService<Student> {
void ifExists(String studentNo);
}
实现类
public class StudentServiceImpl extends AbstractServiceImpl<Student> implements StudentService {
@Override
public void ifExists(String studentNo) {
Condition condition = new Condition(实体.class);
condition.createCriteria().andEqualTo("id",studentNo).andEqualTo("isDeleted",0);
if(findByCondition(condition).size() != 0) {
throw new RuntimeException("学生存在!");
}
}
}