須要額外定義一個查詢類來封裝查詢對象( getXX setXX )。java
編寫mapper.xml文件sql
測試app
package com.ts.dao.vo; import com.ts.domain.Users; /** * 複雜條件查詢VO * @author TS * */ public class UsersQueryVo { private Users users; public Users getUsers() { return users; } public void setUsers(Users users) { this.users = users; } }
package com.ts.domain; import java.util.Date; /*實體Bean*/ public class Users { public Users() {} public Users(String name,Date birth, String sex , String address) { this.name = name; this.sex = sex; this.birth = birth; this.address = address; } private int id; private String name; private String sex; private Date birth; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Users [id=" + id + ", name=" + name + ", sex=" + sex + ", birth=" + birth + ", address=" + address + "]"; } }
<select id="findUserList" parameterType="com.ts.dao.vo.UsersQueryVo" resultType="com.ts.domain.Users"> select * from Users <!-- 能夠自動去掉條件中的第一個and --> <where> <if test="users!=null"> <if test="users.sex!=null and users.sex!=''"> and users.sex = #{users.sex} </if> <if test="users.name!=null and users.name!=''"> and users.name like '%${users.name}%' </if> </if> </where> </select>
//動態SQL測試 @Test public void testDynamicSql() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); UsersQueryVo uv = new UsersQueryVo(); uv.setUsers(new Users("田", null, null, null)); List<Users> list = userMapper.findUserList( null ); System.out.println(list); }
定義SQL片斷
dom
2.引用SQL片斷
ide
<!-- SQL片斷 1.最好基於單表來定義SQL片斷,若是涉及多表查詢,能夠把單表的SQL判斷組合起來。可重用高 2.在SQL片斷裏不要包含where,由於可能一個SQL引用多個SQL片斷。一條SQL只能有一個where條件。 --> <sql id="queryUsersWhere"> <if test="users!=null"> <if test="users.sex!=null and users.sex!=''"> and users.sex = #{users.sex} </if> <if test="users.name!=null and users.name!=''"> and users.name like '%${users.name}%' </if> </if> </sql> <!-- 引用SQL片斷 --> <select id="findUserList" parameterType="com.ts.dao.vo.UsersQueryVo" resultType="com.ts.domain.Users"> select * from Users <where> <include refid = "queryUsersWhere"></include><!-- 若是SQL片斷的id不在本mapper文件中,須要加上namespace --> </where> </select>