mybatis入门使用6:动态SQL

来源:互联网 发布:女孩子学软件测试 编辑:程序博客网 时间:2024/06/08 16:13

在使用mybatis时,有时为减少写接口和mapper,可以使用动态sql。

MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑。 
MyBatis中用于实现动态SQL的元素主要有:if ,where choose(when,otherwise),foreach


1、if :使用if动态sql语句先进行判断,如果值为null或等于空字符串,我们就不进行此条件的判断,增加灵活性。 

2、where:where标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。

<select id="selectByName" resultMap="BaseResultMap" parameterType="java.lang.String" >
select 
<include refid="Base_Column_List" />
from t_employee
<where>
<if test=' name != null and name != "" '>
EmployeeName = #{name}
</if>
</where>
</select>


3、foreach

foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close 。item表示集合中每一个元素进行迭代时的别名;index指定一个名字,用于表示在迭代过程中,每次迭代到的位置;open表示该语句以什么开始;separator表示在每次进行迭代之间以什么符号作为分隔符;close表示以什么结束。

collection:如果传入的是单参数且参数类型是一个List的时候,collection属性值为list;如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array;如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key;

<select id="selectDynamicForeach" resultMap="BaseResultMap" parameterType="java.util.Map" >
select 
<include refid="Base_Column_List" />
from t_employee where ID in 
<foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>

4、choose (when,otherwise)

<choose>标签类似switch,<if>标签内不能再嵌套<if>,可以在 <choose> <when> 中嵌套<if> 再一次提高动态sql的能力。

<select id="selectChoose"  resultMap="BaseResultMap" parameterType="java.util.Map" >
   select 
    <include refid="Base_Column_List" />
    from t_employee 
    <where>
    <choose>  
            <when test="compareType == 1 ">  
                 Salary   &gt; #{salary}
            </when>  
            <when test="compareType == 2">  
                  Salary =  #{salary}
            </when>  
            <otherwise>  
                  Salary &lt;  #{salary} 
            </otherwise>  
        </choose>
        </where>
  </select>

测试:

package com.lls.test;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.lls.mapper.EmployeeMapper;
import com.lls.model.Employee;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:config/spring-mybatis.xml" })
public class DynamicSqlTest {
private static final Logger LOGGER = LoggerFactory.getLogger(DynamicSqlTest.class);
@Autowired
private EmployeeMapper employeeMapper;

@Test
public void testIf() {
List<Employee> all = employeeMapper.selectByName("");
List<Employee> employees = employeeMapper.selectByName("xiaoA");
LOGGER.info("all " + all.size());
LOGGER.info("employees " + employees.size());
}

@Test
public void testForeach() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("departmentId", 1);
List<Integer> ids = new LinkedList<Integer>();
for (int i = 1; i < 10; i++) {
ids.add(i);
}
map.put("ids", ids);
List<Employee> employees = employeeMapper.selectDynamicForeach(map);
LOGGER.info("employees " + employees.size());
}

@Test
public void testOtherWise() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("compareType", 1);
map.put("salary", 13000d);
List<Employee> employeesLt = employeeMapper.selectChoose(map);
map.put("compareType", 2);
LOGGER.info("employeesLt " + employeesLt.size());
List<Employee> employeesGt = employeeMapper.selectChoose(map);
map.put("compareType", 3);
LOGGER.info("employeesGt " + employeesGt.size());
List<Employee> employeesEq = employeeMapper.selectChoose(map);
LOGGER.info("employeesEq " + employeesEq.size());
}
}

代码文档:http://download.csdn.net/download/lanlianhua_luffy/9869769



原创粉丝点击