目录
一、if标签
1、where标签
2、trim标签
二、foreach标签
三、choose标签
四、set标签 - if结合set实现动态更新
五、bind 和include
六、OGNL和其他两个参数
1、OGNL
2、其他两个参数(基本用不上)
简化sql语句动态拼串操作
if test=""中称为OGNL表达式
/*
* if测试*/
@Test
public void test2(){
try(final SqlSession sqlSession = sqlSessionFactory.openSession();) {
final CountMapper mapper = sqlSession.getMapper(CountMapper.class);
final Count countBefore = new Count();
countBefore.setId(1);
countBefore.setName("%尔%");
final List counts = mapper.getCountByCondition(countBefore);
for (Count count : counts) {
System.out.println("count = " + count);
}
sqlSession.commit();
}
}
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
where标签可以去除if标签中多余的and(但只能去除语句开头拼接的and)
/*
* foreach测试*/
@Test
public void test3(){
try(final SqlSession sqlSession = sqlSessionFactory.openSession();) {
final CountMapper mapper = sqlSession.getMapper(CountMapper.class);
final ArrayList ids = new ArrayList<>();
ids.add(2);
ids.add(3);
final List counts = mapper.getCountByIdIn(ids);
for (Count count : counts) {
System.out.println("count = " + count);
}
sqlSession.commit();
}
}
/*
* choose测试*/
@Test
public void test4(){
try(final SqlSession sqlSession = sqlSessionFactory.openSession();) {
final CountMapper mapper = sqlSession.getMapper(CountMapper.class);
final Count countBefore = new Count();
countBefore.setId(1);
countBefore.setName("xxx");
final List counts = mapper.getCountByIdChoose(countBefore);
for (Count count : counts) {
System.out.println("count = " + count);
}
sqlSession.commit();
}
}
分支选择从多个条件中选择一个使用
update count
name=#{name},
gender=#{gender},
email=#{email},
count=#{count},
adress=#{adress},
birthday=#{birthday}
where id=#{id}
/*绑定一个表达式的值到一个变量*/
OGNL:对象导航图语言(Object Graph Navigation Language),简称OGNL,是应用于Java中的一个开源的表达式语言(Expression Language),它被集成在Struts2等框架中,作用是对数据进行访问,它拥有类型转换、访问对象方法、操作集合对象等功能。
在Mybatis中,不仅传入的参数可以用来判断,还有两个属性可以判断
_parameter:代表传入来的参数
(1)传入了单个参数,_parameter就代表这个参数
(2)传入了多个参数,_parameter代表多个参数封装成的map
_databbaseId:代表数据库厂商的id,在全局配置中由databaseIdProvider指定