MyBatis - MyBatis Generator 生成的example 如何使用 and or 简单混合查询
生活随笔
收集整理的這篇文章主要介紹了
MyBatis - MyBatis Generator 生成的example 如何使用 and or 简单混合查询
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
簡單介紹:
Criteria,包含一個Cretiron的集合,每一個Criteria對象內(nèi)包含的Cretiron之間是由AND連接的,是邏輯與的關(guān)系。 oredCriteria,Example內(nèi)有一個成員叫oredCriteria,是Criteria的集合,就想其名字所預(yù)示的一樣,這個集合中的Criteria是由OR連接的,是邏輯或關(guān)系。oredCriteria就是ORed Criteria。 or()方法,會產(chǎn)生一個新的Criteria對象,添加到oredCriteria中,并返回這個Criteria對象,從而可以鏈?zhǔn)奖磉_(dá),為其添加Criterion。查詢條件1:a=? and (b=? or c=?) 不支持
查詢條件2:(a=? And b=?) or (a=? And c=?) 支持
寫法1:
1 DemoExample example=new DemoExample(); 2 3 DemoExample.Criteria criteria1=example.createCriteria(); 4 criteria1.andAEqualTo(?).andBEqualTo(?); 5 6 DemoExample.Criteria criteria2=example.createCriteria(); 7 criteria2.andAEqualTo(?).andCEqualTo(?); 8 9 example.or(criteria2); 10 11 SqlSession sqlSession = MyBatisUtil.openSession(); 12 DemoMapper m = sqlSession.getMapper(DemoMapper.class); 13 m.countByExample(example); 14 //生成的sql語句 15 select count(*) from demo WHERE ( a = ? and b = ? ) or ( a = ? and c = ? )?
寫法2:
1 DemoExample example=new DemoExample(); 2 3 example.or().andAEqualTo(?).andBEqualTo(?); 4 example.or().andAEqualTo(?).andCEqualTo(?); 5 6 SqlSession sqlSession = MyBatisUtil.openSession(); 7 DemoMapper m = sqlSession.getMapper(DemoMapper.class); 8 m.countByExample(example); 9 //生成的sql語句 10 select count(*) from demo WHERE ( a = ? and b = ? ) or ( a = ? and c = ? )?查詢條件3:(a=? and (b=? or c=?)) 支持
假設(shè)兩個搜索項(xiàng),A項(xiàng)搜索,可搜索b,c(bc或關(guān)系),B項(xiàng)搜索可搜索a,B項(xiàng)搜索與A項(xiàng)搜索是與關(guān)系。
修改DemoExample.java文件,新增方法
?
1 public Criteria andOrDemo(String value){ 2 addCriterion("(b = \""+value+"\" or c = \""+value+"\")"); 3 return (Criteria) this; 4 }?
DemoAction.java
1 DemoExample example=new DemoExample(); 2 Criteria criteria = example.createCriteria(); 3 criteria.andAEqualTo(?).andOrDemo(?); 4 5 SqlSession sqlSession = MyBatisUtil.openSession(); 6 DemoMapper m = sqlSession.getMapper(DemoMapper.class); 7 m.countByExample(example); 8 //生成的sql語句 9 select count(*) from demo WHERE ( a = ? and ( b = ? or c = ? ))?
?
寫法1:
?
轉(zhuǎn)載于:https://www.cnblogs.com/kangping/p/6001519.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的MyBatis - MyBatis Generator 生成的example 如何使用 and or 简单混合查询的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 字典常用的方法(内建函数)
- 下一篇: 20169210 2016-2017-2