这篇文章主要介绍了mybatis中的动态sql问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是通过标签解决拼接SQL语句字符串时的问题
1、if(常用)
if:根据标签中test属性所对应的表达式决定标签中的内容是否需要拼接到SQL中
/** * 多条件查询 */ ListgetEmpByCondition(Emp emp);
当empName为null和“ ”时,会拼接and age,此时会报错,可以1=1恒成立解决。
- 用and表示&&(并且)
- emp_name是字段名
- if只有test标签且必须使用
@Test public void testGetEmpByCondition(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class); Listlist = mapper.getEmpByCondition(new Emp(null, "陈智", 33, "女", null)); System.out.println(list); }
select eid,emp_name,age,sex,email from t_emp where emp_name = ? and age = ? or sex = ?
2、where
当where标签中有内容时,会自动生成where关键字,并且将内容前多余的and或or去掉(在程序执行后生成的sql会将内容前多余的and或or去掉)
and写在第二句是为了和上面拼接,写在第一句是和下面拼接(即固定有elect * from t_emp emp_name= ?)
当where标签中没有内容时(或者使用getEmpByCondition传入的值全为null或“ ”),此时where标签没有任何效果。则直接SQL语句为select * from t_emp
--------------------分割--------------------
where标签不能将其中内容后面多余的and或or去掉:(会报错)
语句为select * from t_emp emp_name= ? and
3、trim
where的增强
若标签中有内容时:
prefix
|suffix
:将trim标签中内容前面或后面添加指定内容suffixOverrides
|prefixOverrides
:将trim标签中内容前面或后面去掉指定内容
若标签中没有内容时,trim标签也没有任何效果(跟上面的where一样)
4.choose、when、otherwise
相当于if...else if...else
/** * 测试choose、when、otherwise */ ListgetEmpByChoose(Emp emp);
when至少要有一个,otherwise最多只能有一个
与第一点if的区别:choose只会满足一个条件便退出,一个不满足则执行otherwise
@Test public void testGetEmpByChoose(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class); Listlist = mapper.getEmpByChoose(new Emp(null, "", null, "", "")); System.out.println(list); }
5、foreach
collection
:设置需要循环的数组或集合item
:表示数组或集合中的每一个数据separator
:循环体之间的分割符open
:foreach标签所循环的所有内容的开始符close
:foreach标签所循环的所有内容的结束符
5.1批量删除
/** * 通过数组实现批量删除 */ int deleteMoreByArray(@Param("eids") Integer[] eids);
delete from t_emp where eid = #{eid}
@Test public void testDeleteMoreByArray(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class); int result = mapper.deleteMoreByArray(new Integer[]{12,13,14,15}); System.out.println(result); }
5.2批量添加
/** * 通过list集合实现批量添加 */ int insertMoreByList(@Param("emps") Listemps);
insert into t_emp values (null,#{emp.empName},#{emp.age},#{emp.sex},#{emp.email},null)
Arrays.asList该方法是将数组转化成List集合的方法
如果你的List只是用来遍历,就用Arrays.asList()。
如果你的List还要添加或删除元素,还是乖乖地new一个java.util.ArrayList,然后一个一个的添加元素。
@Test public void testInsertMoreByList(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class); Emp emp1 = new Emp(null,"a1",23,"男","123@qq.com"); Emp emp2 = new Emp(null,"a2",23,"男","123@qq.com"); Emp emp3 = new Emp(null,"a3",23,"男","123@qq.com"); Listemps = Arrays.asList(emp1, emp2, emp3); System.out.println(mapper.insertMoreByList(emps)); }
6、sql标签
设置SQL片段:
引用SQL片段:
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持0133技术站。
以上就是mybatis中的动态sql问题的详细内容,更多请关注0133技术站其它相关文章!