trim标签体中是整个字符串拼串后的结果。
prefix="" 前缀: prefix给拼串后的整个字符串加一个前缀
prefixOverrides="" 前缀覆盖: 去掉整个字符串前面多余的字符
suffix="" 后缀: suffix给拼串后的整个字符串加一个后缀
suffixOverrides="" 后缀覆盖:去掉整个字符串后面多余的字符
示例代码:
接口定义:
package com.mybatis.dao;
import com.mybatis.bean.Employee;
import java.util.List;
public interface EmployeeMapper {
public List<Employee> getEmpsByConditionTrim(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> getEmpsByConditionTrim(Employee employee); -->
<select id="getEmpsByConditionTrim" resultType="com.mybatis.bean.Employee">
select * from tbl_employee
<!--
后面多出的and或者or where标签不能解决
trim标签体中是整个字符串拼串后的结果。
prefix="" 前缀:prefix给拼串后的整个字符串加一个前缀
prefixOverrides="" 前缀覆盖: 去掉整个字符串前面多余的字符
suffix="" 后缀 suffix给拼串后的整个字符串加一个后缀
suffixOverrides="" 后缀覆盖:去掉整个字符串后面多余的字符
-->
<!-- 自定义字符串的截取规则 -->
<trim prefix="where" prefixOverrides="and">
<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>
<if test="gender==0 or gender==1">
and gender=#{gender}
</if>
</trim>
</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);
List<Employee> emps = mapper.getEmpsByConditionTrim(new Employee(null, "jetty", "jetty@126.com", 1));
for (Employee emp : emps) {
System.out.println(emp);
}
} finally {
openSession.close();
}
}
}