动态SQL的if和when的使用方法
映射文件CustomerMapper.xml使用if元素编写根据客户姓名和职业组合查询客户信息
<mapper namespace="com.itheima.mapper.CustomerMapper">
<select id="findCustomerById" parameterType="Customer"
resultType="Customer">
select *from customer where 1=1
<if test="username!=null and username!=''">
and username like concat('%',#{username},'%')
</if>
<if test="jobs!=null and jobs!=''">
and jobs=#{jobs}
</if>
</select>
if的test 属性分别对username和jobs进行非空判断,如果不为空就进行动态SQL组装。
测试类
private SqlSession sqlSession=null;
@Before
public void setUp() throws Exception {
sqlSession=SqlSessionFactoryUtil.openSession();
}
@After
public void tearDown() throws Exception {
sqlSession.close();
}
@Test
public void findCustomer() {
Customer customer =new Customer();
customer.setUsername("jack");
customer.setJobs("22");
List<Customer> customers =sqlSession.selectList("com.itheima.mapper"+".CustomerMapper.findCustomerById",customer);
for(Customer customer2:customers) {
System.out.println(customer2);
}
}
工具类SqlSession
package com.itheima.util;
import java.io.InputStream;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class SqlSessionFactoryUtil {
private static SqlSessionFactory sqlSessionFactory;
public static SqlSessionFactory getSqlSessionFactory(){
if(sqlSessionFactory==null){
InputStream inputStream=null;
try{
inputStream=Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
}catch(Exception e){
e.printStackTrace();
}
}
return sqlSessionFactory;
}
public static SqlSession openSession(){
return getSqlSessionFactory().openSession();
}
}
when元素执行SQL代码
<select id="findCustomerByNameOrJobs" parameterType="Customer" resultType="Customer">
select *from customer where 1=1
<choose>
<when test="username!=null and username!=''">
and username like concat('%',#{username},'%')
</when>
<when test="jobs !=null and jobs!=''">
and jobs=#{jobs}
</when>
<otherwise>
and phone is not null
</otherwise>
</choose>
</select>
当第一个when元素中的执行条件为真,则只动态组装第一个when元素的SQL,否则就继续判断第二个when元素中的条件是否为真。
when元素测试类
@Test
public void findCustomerBy() {
Customer customer =new Customer();
/* customer.setUsername("jack");*/
customer.setJobs("teacher");
List<Customer> customers =sqlSession.selectList("com.itheima.mapper"+".CustomerMapper.findCustomerByNameOrJobs",customer);
for(Customer customer2:customers) {
System.out.println(customer2);
}
}