MyBatis使用example类

MyBatis 的 Example

逆向工程 中,我们可以根据数据库的表自动生产 MyBatis 所需的 mapper.java、mapper.xml、po.java、poExample.java。前三个我们已经非常熟悉了,而未使用过 poExample 类,直到最近在项目中碰到了,在这里总结一下。

Example
Example类指定了如何构建一个动态的 where 子句. 表中的每个表的列可以被包括在 where 子句中。主要用于简化我们 sql 语句的编写。
Example类包含一个内部静态类 Criteria,而 Criteria中 的方法是定义 SQL 语句 where 后的查询条件。Criteria 对象可以通过 example 对象的 createCriteria 方法创建。

要生成 Example,需要注意下 generatorConfig.xml 里的配置:

    <table tableName="user" domainObjectName="User">
	    <!--
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
            -->
    </table>
复制代码

Criteria 中的常用方法

案例

  1. 使用 criteria:

    UserExample example =new UserExample();//由逆向工程生成
    Criteria criteria = example.createCriteria();
    criteria.setOrderByClause("id des");//按 id 字段降序
    criteria.andUsernameEqualTo("zhangsan");
    List<User> list = userMapper.selectByExample(example);
    // sql:select * from t_user where name=zhangsan order by id des		
    复制代码
  2. 不使用 criteria:

    UserExample example = new UserExample(); 
    example.and() 
           .andEqualTo("id", id) 
       .andEqualTo("name", name); //example.and()底层还是返回的criteria
    List<User> list = userMapper.selectByExample(example);
    复制代码
  3. and 和 or

    UserExample example = new UserExample(); 
    Criteria cri1 = example.createCriteria(); 
    Criteria cri2 = example.createCriteria(); 
    cri1.andIn("id", ids); 
    cri2.orLike("des", "%" + des + "%"); 
    cri2.orLike("name", "%" + name + "%"); 
    example.and(cri2);//example.or(cri2);
    // where (id in ids) and (name like %des% or des like %name%)
    复制代码