mybatis generator中Example的使用

本文介绍如何使用MyBatis的Example类构建复杂的查询条件,通过组合AND和OR逻辑来形成灵活的查询语句。文章展示了如何创建Criteria对象,并通过链式调用设置不同的查询条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

example用来构造复杂的条件语句使用的,example里面包含了一个Criteria(他是一个条件集),Criteria中有许多Cretiron,cretiron之间是用and连接,是逻辑与关系

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

TestTableExample example = new TestTableExample();
 
  example.or()
    .andField1EqualTo(5)
    .andField2IsNull();
 
  example.or()
    .andField3NotEqualTo(9)
    .andField4IsNotNull();
 
  List<Integer> field5Values = new ArrayList<Integer>();
  field5Values.add(8);
  field5Values.add(11);
  field5Values.add(14);
  field5Values.add(22);
 
  example.or()
    .andField5In(field5Values);
 
  example.or()
    .andField6Between(3, 7);


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

产生的动态SQL是这样的


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)


我们再来看下更深一步的实现:

 

TestTableExample example=new TestTableExample();  

TestTableExample.Criteria criteria1=example.createCriteria();  
criteria1.andField1EqualTo(5).andField2IsNull();  
          
TestTableExample.Criteria criteria2=example.createCriteria();  
criteria2.andAEqualTo(3).andCEqualTo(4); example.or(criteria2); SqlSession sqlSession = MyBatisUtil.openSession();TestTableMapper m = sqlSession.getMapper(TestTableMapper.class);m.countByExample(example); //生成的sql语句select count(*) from demo WHERE ( field1 = 5 and field2 is null ) or ( a = 3 and c = 4 )





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值