通用mapper tk.mybatis A and (B OR C)
使用通用mapper时可以方便我们少写sql但是,有时候他生成的语句并不一定是我们想要的
比如 我的需求是 查询 A and (B or C)
例如
SELECT * FROM T WHERE ID IN (1,2,3) AND (code LIKE "%A%" OR name LIKE "%B%")
错误的写法:
Example example = new Example(TEdiTiktokExpand.class);
Example.Criteria criteria = example.createCriteria();
criteria.andIn("ID", Arrays.asList("1","2","3"));
Example.Criteria criteriaLike = example.createCriteria();
criteriaLike.andLike("code", "%A%").orLike("name", "%B%");
Dao.selectByExample(example);
上面的SQL 的语句为
SELECT * FROM T WHERE(ID IN (1,2,3) AND code LIKE "%A%" OR name LIKE "%B%" )
显然不是我们需要的 我们希望 code和name的条件在同一个括号内
正确的写法:
Example example = new Example(TEdiTiktokExpand.class);
Example.Criteria criteria = example.createCriteria();
criteria.andIn("code", Arrays.asList("1","2","3"));
Example.Criteria criteriaLike = example.createCriteria();
criteriaLike.andLike("code", "%A%").orLike("name", "%B%");
//如果你需要 两个条件在同一个括号 需要单独创建一个Criteria 然后使用example.and();就可以了
example.and(criteriaLike);
Dao.selectByExample(example);
生成的语句为:
SELECT * FROM T WHERE ( ( ID in ( ? , ? , ? ) ) and ( code like "%A%" or name like "%B%" ) )