使用mybatis动态where字句方法

        上篇文章介绍了如何使用mybatis-generator生成实体类、Mapper接口代码,其中生成的Mapper接口代码是不带ByExample方法的。本篇文章将介绍如何使用mybatis-generator生成的ByExample方法动态扩展where字句。


 

一、Mapper接口生成ByExample方法

(1)下载上篇文章的demo:https://github.com/Bingjian-Zhu/MybatisGeneatorDemo.git

 

(2)修改generatorConfig.xml配置文件

把context元素中的targetRuntime属性修改成MyBatis3

<context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">

 

(3)重新运行MBG,可以看到生成了很多ByExample的方法

 

 


 

二、mapper接口中的方法解析

方法

功能说明

int countByExample(UserExample example) thorws SQLException

按条件计数

int deleteByPrimaryKey(Integer id) thorws SQLException

按主键删除

int deleteByExample(UserExample example) thorws SQLException

按条件查询

String/Integer insert(User record) thorws SQLException

插入数据(返回值为ID)

User selectByPrimaryKey(Integer id) thorws SQLException

按主键查询

List selectByExample(UserExample example) thorws SQLException

按条件查询

int updateByPrimaryKey(User record) thorws SQLException

按主键更新

int updateByPrimaryKeySelective(User record) thorws SQLException

按主键更新值不为null的字段

int updateByExample(User record, UserExample example) thorws SQLException

按条件更新

int updateByExampleSelective(User record, UserExample example) thorws SQLException

按条件更新值不为null的字段

 


 

三、example实例解析

MBG生成实例及实例对应的ByExample,Example用于添加条件,相当where后面的部分

xxxExample example = new xxxExample();

Criteria criteria = new Example().createCriteria();

方法

功能说明

example.setOrderByClause(“字段名 ASC”);

添加升序排列条件,DESC为降序

example.setDistinct(false)

去除重复,boolean型,true为选择不重复的记录。

criteria.andXxxIsNull

添加字段xxx为null的条件

criteria.andXxxIsNotNull

添加字段xxx不为null的条件

criteria.andXxxEqualTo(value)

添加xxx字段等于value条件

criteria.andXxxNotEqualTo(value)

添加xxx字段不等于value条件

criteria.andXxxGreaterThan(value)

添加xxx字段大于value条件

criteria.andXxxGreaterThanOrEqualTo(value)

添加xxx字段大于等于value条件

criteria.andXxxLessThan(value)

添加xxx字段小于value条件

criteria.andXxxLessThanOrEqualTo(value)

添加xxx字段小于等于value条件

criteria.andXxxIn(List<?>)

添加xxx字段值在List<?>条件

criteria.andXxxNotIn(List<?>)

添加xxx字段值不在List<?>条件

criteria.andXxxLike(“%”+value+”%”)

添加xxx字段值为value的模糊查询条件

criteria.andXxxNotLike(“%”+value+”%”)

添加xxx字段值不为value的模糊查询条件

criteria.andXxxBetween(value1,value2)

添加xxx字段值在value1和value2之间条件

criteria.andXxxNotBetween(value1,value2)

添加xxx字段值不在value1和value2之间条件

 


 

四、具体使用

(1)查询

① selectByPrimaryKey()

User user = XxxMapper.selectByPrimaryKey(100); //相当于select * from user where id = 100

② selectByExample() 

UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("wyw");
criteria.andUsernameIsNull();
example.setOrderByClause("username asc,email desc");
List<?>list = XxxMapper.selectByExample(example);

//相当于:select * from user where username = 'wyw' and  username is null order by username asc,email desc

 

(2)插入数据

①insert()

User user = new User();
user.setId("dsfgsdfgdsfgds");
user.setUsername("admin");
user.setPassword("admin")
user.setEmail("wyw@163.com");
XxxMapper.insert(user);

//相当于:insert into user(ID,username,password,email) values ('dsfgsdfgdsfgds','admin','admin','wyw@126.com');

 

(3)更新数据

①updateByPrimaryKey()

User user =new User();
user.setId("dsfgsdfgdsfgds");
user.setUsername("wyw");
user.setPassword("wyw");
user.setEmail("wyw@163.com");
XxxMapper.updateByPrimaryKey(user);

//相当于:update user set username='wyw', password='wyw', email='wyw@163.com' where id='dsfgsdfgdsfgds'

②updateByPrimaryKeySelective()

User user = new User();
user.setId("dsfgsdfgdsfgds");
user.setPassword("wyw");
XxxMapper.updateByPrimaryKey(user);

//相当于:update user set password='wyw' where id='dsfgsdfgdsfgds'

③ updateByExample() 和 updateByExampleSelective()

UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("admin");
User user = new User();
user.setPassword("wyw");
XxxMapper.updateByPrimaryKeySelective(user,example);

//相当于:update user set password='wyw' where username='admin'

updateByExample()更新所有的字段,包括字段为null的也更新,建议使用 updateByExampleSelective()更新想更新的字段

 

(4)删除数据

①deleteByPrimaryKey()

XxxMapper.deleteByPrimaryKey(1);  //相当于:delete from user where id=1

②deleteByExample()

UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("admin");
XxxMapper.deleteByExample(example);

//相当于:delete from user where username='admin'

 

(5)查询数据数量

①countByExample()

UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("wyw");
int count = XxxMapper.countByExample(example);

//相当于:select count(*) from user where username='wyw'

 


 

五、pagehelper分页

(1)配置pom

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.10</version>
            <exclusions>
            <exclusion>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
            </exclusion>
        </exclusions>
        </dependency>

 

(2)在application.properties配置pagehelper的属性

pagehelper.helperDialect=mysql
pagehelper.reasonable=true  #为了使用输入页数为负或者超出最大页时候使页数为最小或最大值
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

 

(3)进行分页

PageHelper.startPage(pageNum, pageSize);

 

(4)按需返回数据

以上3步已实现分页,如需返回以下类型数据,可实现Serializable接口,自定义数据返回类型

 

 

@SuppressWarnings("rawtypes")
public class MyPageInfo<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    // 总记录数
    protected long total;
    // 当前页
    protected int pageNum;
    // 每页的数量
    protected int pageSize;
    // 结果集
    protected List<T> list;
    public MyPageInfo() {
    }
    /**
     * 包装Page对象
     *
     * @param list
     */
    public MyPageInfo(List<T> list) {
        this.list = list;
        if (list instanceof Page) {
            Page page = (Page) list;
            this.pageNum = page.getPageNum();
            this.pageSize = page.getPageSize();
            this.total = page.getTotal();
        } else {
            this.pageNum = 1;
            this.pageSize = list.size();
            this.total = list.size();
        }
    }

    public static <T> MyPageInfo<T> of(List<T> list) {
        return new MyPageInfo<T>(list);
    }

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("MyPageInfo{");
        sb.append("total=").append(total);
        sb.append(", pageNum=").append(pageNum);
        sb.append(", pageSize=").append(pageSize);
        sb.append(", list=").append(list);
        sb.append('}');
        return sb.toString();
    }
}

具体使用:

    public MyPageInfo<User> getAllUsers(String userName, Boolean deleted, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        if (userName != null && !StringUtils.isEmpty(userName.trim()))
            criteria.andUserNameLike("%" + userName.trim() + "%");
        if (deleted != null)
            criteria.andDeletedEqualTo(deleted);
        example.setOrderByClause("id asc");
        List<User> list = userMapper.selectByExample(example);
        MyPageInfo<User> pageInfo = new MyPageInfo<User>(list);
        return pageInfo;
}

 


 

源码地址:https://github.com/Bingjian-Zhu/MybatisByExampleDemo.git

参考博客:https://blog.csdn.net/biandous/article/details/65630783#commentBox

posted @ 2019-07-18 10:04  烟花易冷人憔悴  阅读(1801)  评论(1编辑  收藏  举报