mybatis的condition使用

实体类等不赘述。
1.新建一个BaseMapper文件,继承几种基础mapper,可根据需求自行添加

public interface MyMapper
        extends BaseMapper,
        ConditionMapper,
        IdsMapper,
        ExampleMapper,
        InsertListMapper,
        MySqlMapper {
}

2.新建一个BaseService,此处仅添加根据condition查找的方法,可自行添加其他需要使用的一些方法。

public interface MyBaseService {
    void deleteByCondition(T model, Condition condition);
    List findByCondition(Condition condition);
}

3.实现BaseService

public abstract class AbstractServiceImpl implements MyService {

    @Autowired
    protected MyMapper mapper;

    private Class modelClass;

    public AbstractServiceImpl() {
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        modelClass = (Class) pt.getActualTypeArguments()[0];
    }

    public void deleteByCondition(T model, Condition condition) {
        mapper.updateByConditionSelective(model,condition);
    }

    public List findByCondition(Condition condition) {
        return mapper.selectByCondition(condition);
    }

}

4.在方法实现类下引用
接口定义

public interface StudentService extends MyBaseService {
    void ifExists(String studentNo);
}

实现类

public class StudentServiceImpl extends AbstractServiceImpl 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("学生存在!");
        }
    }
}

你可能感兴趣的:(mybatis的condition使用)