Mybatis-- 初步了解Example类

1. 什么是example类

Example类指定如何构建一个动态的where子句. 表中的每个non-BLOB列可以被包括在where子句中. 例子是展示此类用法的最好方式.

Example类可以用来生成一个几乎无限的where子句.

Example类包含一个内部静态类 Criteria 包含一个用 anded 组合在where子句中的条件列表. Example类包含一个 List 属性,所有内部类Criteria中的子句会用 ored组合在一起. 使用不同属性的 Criteria 类允许您生成无限类型的where子句.

创建 Criteria 对象 可以使用Example类中的 createCriteria() 或者 or() . 如果 Criteria 对象是用 createCriteria() 创建的,它会自动为 List 属性添加一个 Criteria 对象 - 这使得它更容易写一个简单的where子句, 如果您不需要 or 或者其他几个子句组合的话. 用 or(Criteria criteria) 方法创建 Criteria 对象, 方法里的 criteria 对象会被添加进 Criteria 对象的列表中.

重要 我们推荐您只使用 or() 方法创建 Criteria 对象. 我们相信这种方法使代码更有可读性.

2. Criterion

Criterion是最基本、最底层的Where条件,用于字段级的筛选,field用于指代字段名字

列举如下:

只有一个条件,不需要其他参考值
field IS NULL
field IS NOT NULL

与一个参考值进行算数运算
field > value
field >= value
field = value
field <> value
field <= value
field < value

与一个参考值进行模糊查询,参值中的%,?只能在构造查询条件时手动指定。

field LIKE value
field NOT LIKE value

介于两个参考值之间

field BETWEEN value AND secondValue

在或不在一个参考值集合中,item来自于value集合

field IN (item, item, item,…)
field NOT IN (item, item, item, …)

MyBatis Generator会为每个字段产生如上的Criterion,如果表的字段比较多,产生的Example类会十分庞大。理论上通过Example类可以构造你想到的任何筛选条件。

3. Criteria

包含一个Cretiron的集合,每一个Criteria对象内包含的Cretiron之间是由AND连接的,是逻辑与的关系。

4. oredCriteria

Example内有一个成员叫oredCriteria,是Criteria的集合,就想其名字所预示的一样,这个集合中的Criteria是由OR连接的,是逻辑或关系。oredCriteria就是ORed Criteria。

or()方法,会产生一个新的Criteria对象,添加到oredCriteria中,并返回这个Criteria对象,从而可以链式表达,为其添加Criterion。

查询条件1:a=? and (b=? or c=?) 不支持

查询条件2:(a=? and b=?) or (a=? and c=?) 支持

5. 用法
  • 用生成后的Example类去生成一个简单的where子句:
TestTableExample example = new TestTableExample();
example.createCriteria().andField1EqualTo(5);   

TestTableExample example = new TestTableExample();
example.or().andField1EqualTo(5); 

在上面的例子中, 动态生成的where子句是:

where field1 = 5

  • 用生成后的Example类去生成一个复杂的where子句
TestTableExample example = new TestTableExample();

example.or() 
.andField1EqualTo(5) 
.andField2IsNull();

example.or() 
.andField3NotEqualTo(9) 
.andField4IsNotNull();

List field5Values = new ArrayList(); 
field5Values.add(8); 
field5Values.add(11); 
field5Values.add(14); 
field5Values.add(22);

example.or() 
.andField5In(field5Values);

example.or() 
.andField6Between(3, 7);

在上面的例子中, 动态生成的where子句是:

where (field1 = 5 and field2 is null) 
or (field3 <> 9 and field4 is not null) 
or (field5 in (8, 11, 14, 22)) 
or (field6 between 3 and 7) 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值