工具:mybatis+pgsql
注意:
以下三種判斷查詢的結果是不一樣的
<if test = "column != null">
<if test = "column != null and column != '' ">
<if test = "column != '' ">
數據庫數據如下:
id username sex address depId status
1 張三 男 上海 001 1
2 李四 女 上海 1
3 王五 女 上海 002 1
案例1
dao層
User select(String username,String depId);
sql
<select id = "select" resultType = "com.test.dto.User">
select username,address,sex
from user
where status = 1
and username = #{username}
<if test = "depId != null">
and depId = #{depId}
</if>
</select>
案例2
dao層
List<User> list(String address);
sql
<select id = "list" resultType = "com.test.dto.User">
select username,address,sex
from user
where sex = '女'
<if test = "address != null and address != '' ">
and address like '%' || #{address} || '%'
</if>
</select>
案例3
dao層
List<User> list(String address);
sql
<select id = "list" resultType = "com.test.dto.User">
select username,address,sex
from user
where sex = '女'
<if test = "address != '' ">
and address like '%' || #{address} || '%'
</if>
</select>