通用mapper 根據條件修改、查詢 Example的實例函數及例子

**

通用mapper 根據條件修改、查詢 Example的實例函數及例子

**
條件:
Example example = new Example(User.class);
Criteria criteria = example.createCriteria();

注意:
criteria.andEqualTo(property, value);
property 對應的是實體類中的屬性字段
1、根據條件查詢


    /**
     * 根據名稱,id,ntype等獲取其對應節點總數
     * 用於判斷名稱是否重複
     */
    public int getCountByNameAndUId(String name, Long id, Long userId) {

        Example example = new Example(User.class);
        Criteria criteria = example.createCriteria();


        criteria.andEqualTo("name", name);
        criteria.andNotEqualTo("id", id);
        criteria.andEqualTo("userId", uid);

        int count = categoryMapper.selectCountByExample(example);

        return count;
    }

等效於:
Select count(0) from user where name = #{name} and id != #{id} and uid != #{uid}

2、and or 查詢

public Example test(List<Long> ids, String name, String des) {
Example example = new Example(User.getClass());
        // where 條件
        Criteria criteria = example.createCriteria();
        Criteria criteria1 = example.createCriteria();


        criteria.andIn("id", ids);
        criteria1.orLike("des", "%" + des + "%");
        criteria1.orLike("name", "%" + name + "%");
        example.and(criteria1);

       return example;
}

等效於:
 where id in ( #{ids} ) and ( name like concat(‘%’, #{name} ,’%’) or des like concat(‘%’, #{des} ,’%’) )

3、根據條件修改

    Example example = new Example(User.getClass());
        // where 條件
        Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name", name);
        userMapper.updateByExampleSelective(user, example);
等效於:
Update user set ... where name = #{name}

參照:
MyBatis的Mapper接口以及Example的實例函數及詳解(http://blog.csdn.net/biandous/article/details/65630783)
通用mapper

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章