MyBatis - MyBatis Generator 生成的example 如何使用 and or 简单混合查询
生活随笔
收集整理的這篇文章主要介紹了
MyBatis - MyBatis Generator 生成的example 如何使用 and or 简单混合查询
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
簡單介紹:
Criteria,包含一個Cretiron的集合,每一個Criteria對象內包含的Cretiron之間是由AND連接的,是邏輯與的關系。 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=?) 支持
寫法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=?)) 支持
假設兩個搜索項,A項搜索,可搜索b,c(bc或關系),B項搜索可搜索a,B項搜索與A項搜索是與關系。
修改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:
?
轉載于:https://www.cnblogs.com/kangping/p/6001519.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的MyBatis - MyBatis Generator 生成的example 如何使用 and or 简单混合查询的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 字典常用的方法(内建函数)
- 下一篇: 20169210 2016-2017-2