Mybatis中的动态sql标签,if标签,where标签和foreach标签
if,where
有些时候我们可能需要实现根据用户输入的价格的最高价格,最低价格排序
这个时候那么就可以使用sql动态标签,减去多余的代码,给我们带来方便
话不多说,上代码
我的例在员工表(Emp)是根据员工的工资(salary)筛选
在此之前需要获取SqlSession对象
//再次之前声明一个全局变量SqlSession对象
private SqlSession session = null;
@Before
public void getSession() throws Exception{
//1.去读mybatis核心配置文件
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
//2.获取SqlSessionFactory对象
SqlSessionFactory fac = new SqlSessionFactoryBuilder().buid(in);
//3.获取SqlSession对象,传一个boolean值,是让mybatis自动开启事务
session = fac.getSession(true);
//测试一些session对象创建成功了没
System.out.println("session...... :" + session);
}
<!-- Mapper文件内容:
* 练习12: 根据薪资查询员工信息
* 如果没有参数, 则不执行where子句, 默认查询所有员工:
* select * from emp
* 如果参数中只有minSal(即minSal不为null), 则:
* ... where salary > minSal
* 如果参数中只有maxSal(即maxSal不为null), 则:
* ... where salary < maxSal
* 如果参数有 minSal、maxSal(即minSal、maxSal不为null), 则:
* ... where salary > minSal and salary < maxSal -->
<select id="select12" resultType="com.codew.pojo.Emp">
select * from emp
<!-- where标签:判断其里边的标签内容是否成立,决定需不需要添加where关键语句,在有些时候会自动的去除多余的连接词(如:and和or) -->
<where>
<!-- if标签:根据test的值判断是否添加相应语句
test:boolean -->
<!-- <=(小于等于) 需要转义一下< -->
<!-- >=(大于等于) 需要转义一下> -->
<if test="minSal != null">
and salary >= #{minSal}
</if>
<if test="maxSal != null">
<!-- and salary <![CDATA[ < ]]> #{maxSal} -->
and salary <= #{maxSal}
</if>
</where>
</select>
/* java代码 */
@Test
public void testFindBySal() {
Map<String, Object> map = new HashMap<String, Object>();
//map.put( "minSal" , 3000 );
//map.put( "maxSal", 4000 );
List<Emp> list = session.selectList( "EmpMapper.findBySal", map );
for (Emp emp : list) {
System.out.println( emp );
}
}
foreach
顾名思义,foreach对传过来的集合或者数组进行遍历
foreach的元素介绍:
元素名 | 元素介绍 |
---|---|
item | 元素,便利的时候用来存储单个的元素 |
collection | 如果传的参数仅仅是一个数组或者List集合, collection可以指定为array或list; 如果传的是多个参数,用map封装,collection则指定为map中的key |
open | 表示sql语句从什么地方开始,可选 |
close | 表示sql语句从什么地方结束,可选 |
seperator | 可以给每次遍历sql片段后面添加间隔符,可选 |
话不多说,上代码
/*练习14: 根据员工的id批量删除员工信息 */
@Test
public void testDeleteByIds14(){
Integer[] ids = {2,4,6,8};
session.delete("EmpMapper.deleteByids14",ids);
}
/*
* 练习15: 根据员工的id批量更新员工信息
* 将id为 2、4、6、8的员工的薪资在原有基础上增加1000
*/
@Test
public void testUpdateByIds15(){
Double salary = 1000;
Integer[] ids = {2,4,6,8};
Map<String,Object> map = new HashMap<String,Object>();
Map<String, Object> map = new HashMap<String, Object>();
map.put( "ids" , ids );
map.put( "salary", salary );
int rows = session.deleteByIds15("EmpMapper.updateByIds15",map);
System.out.println( "影响行数: "+rows );
}
<!-- 练习14: 根据员工的id批量删除员工信息 -->
<delete id="">
delete from emp
where id in
<!-- 这里传入的是数组 -->
<foreach collection="array" open="(" item="id" separator="," close=")">
#{id}
</foreach>
</delete>
<!-- 练习15: 根据员工的id批量更新员工信息 -->
<update id="updateByIds15">
update
emp
set
salary = salary + #{salary},
where id in
<foreach collection="ids" open="(" item="id" separator="," close=")">
#{id}
</foreach>
</update>