示例代码:
接口定义:
package com.mybatis.dao;
import com.mybatis.bean.Employee;
import java.util.List;
public interface EmployeeMapper {
//携带了哪个字段查询条件就带上这个字段的值
public List<Employee> getEmpsByConditionIf(Employee employee);
public List<Employee> getEmpsByConditionIfWhere(Employee employee);
}
mapper定义:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.dao.EmployeeMapper">
<!-- 查询员工,要求,携带了哪个字段查询条件就带上这个字段的值 -->
<!-- public List<Employee> getEmpsByConditionIf(Employee employee); -->
<select id="getEmpsByConditionIf" resultType="com.mybatis.bean.Employee">
select * from tbl_employee
where 1=1
<if test="id!=null">
and id=#{id}
</if>
<if test="lastName!=null && lastName!=''">
and last_name like #{lastName}
</if>
<if test="email!=null and email.trim()!=""">
and email=#{email}
</if>
<!-- ognl会进行字符串与数字的转换判断 "0"==0 -->
<if test="gender==0 or gender==1">
and gender=#{gender}
</if>
</select>
<!--public List<Employee> getEmpsByConditionIfWhere(Employee employee);-->
<select id="getEmpsByConditionIfWhere" resultType="com.mybatis.bean.Employee">
select * from tbl_employee
<where>
<if test="id!=null">
id=#{id}
</if>
<if test="lastName!=null && lastName!=''">
and last_name like #{lastName}
</if>
<if test="email!=null and email.trim()!=""">
and email=#{email}
</if>
<!-- ognl会进行字符串与数字的转换判断 "0"==0 -->
<if test="gender==0 or gender==1">
and gender=#{gender}
</if>
</where>
</select>
</mapper>
测试代码:
package com.mybatis.demo;
import com.mybatis.bean.Employee;
import com.mybatis.dao.EmployeeMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyTest {
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void test() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession(true);
try {
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
//查询的时候如果某些条件没带可能sql拼装会有问题
//1、给where后面加上1=1,以后的条件都and xxx.
//2、mybatis使用where标签来将所有的查询条件包括在内。mybatis就会将where标签中拼装的sql,多出来的and或者or去掉
//where只会去掉第一个多出来的and或者or。
List<Employee> emps = mapper.getEmpsByConditionIf(new Employee(null, "jetty", "jetty@126.com", 1));
for (Employee emp : emps) {
System.out.println(emp);
}
System.out.println("-------------------");
List<Employee> employees = mapper.getEmpsByConditionIfWhere(new Employee(null, "jetty", "jetty@126.com", 1));
for (Employee emp : employees) {
System.out.println(emp);
}
} finally {
openSession.close();
}
}
}