trim配合prefix,prefixOverrides,suffix,suffixOverrides構建動態sql語句


1.在接口構建方法

public interface EmployeeMapperDynamicSQL {
//攜帶了哪個字段查詢條件就帶上這個字段的值
public List<Employee> getEmpsByConditionIf(Employee employee);

}

2在映射文件進行配置

<!--public List<Employee> getEmpsByConditionTrim(Employee employee); -->
<select id="getEmpsByConditionTrim" resultType="com.atguigu.mybatis.bean.Employee">
select * from tbl_employee
<!-- 后面多出的and或者or where標簽不能解決
prefix="":前綴:trim標簽體中是整個字符串拼串 后的結果。
prefix給拼串后的整個字符串加一個前綴
prefixOverrides="":
前綴覆蓋: 去掉整個字符串前面多余的字符
suffix="":后綴
suffix給拼串后的整個字符串加一個后綴
suffixOverrides=""
后綴覆蓋:去掉整個字符串后面多余的字符

-->
<!-- 自定義字符串的截取規則 -->
<trim prefix="where" suffixOverrides="and">
<if test="id!=null">
id=#{id} and
</if>
<if test="lastName!=null &amp;&amp; lastName!=&quot;&quot;">
last_name like #{lastName} and
</if>
<if test="email!=null and email.trim()!=&quot;&quot;">
email=#{email} and
</if>
<!-- ognl會進行字符串與數字的轉換判斷 "0"==0 -->
<if test="gender==0 or gender==1">
gender=#{gender}
</if>
</trim>
</select>

3執行sql語句

@Test
public void testDynamicSql() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
Employee employee = new Employee(null, "jerry2", null, null);
//查詢的時候如果某些條件沒帶可能sql拼裝會有問題
//1、給where后面加上1=1,以后的條件都and xxx.
//2、mybatis使用where標簽來將所有的查詢條件包括在內。mybatis就會將where標簽中拼裝的sql,多出來的and或者or去掉
//where只會去掉第一個多出來的and或者or。

//測試Trim
// List<Employee> emps2 = mapper.getEmpsByConditionTrim(employee);
// for (Employee emp : emps2) {
// System.out.println(emp);
// }





}finally{
openSession.close();
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM