1.接口
public interface MemberMapperDynamicSQL { public List<Members> selectMembersByIf(Members member); }
2.配置文件
<mapper namespace="com.dao.MemberMapperDynamicSQL"> <!-- OGNL表达式 &的转义字符为 & ‘的转义字符为 " --> <select id="selectMembersByIf" resultType="members"> select * from members where 1 = 1 <if test="id != null && id != """> and id = #{id} </if> <if test="member_name != null && member_name != """> and member_name like #{member_name} </if> </select> </mapper>
3.测试
public static void main(String[] args) throws IOException { SqlSession session = getSqlSession(); try { // 面向接口方式 MemberMapperDynamicSQL mapper = session.getMapper(MemberMapperDynamicSQL.class); Members member = new Members(); // member.setId(1); // member.setMember_name("%云%"); List<Members> list = mapper.selectMembersByIf(member); System.out.println(list); session.commit(); } finally { // 关闭session session.close(); } }
4.在全局配置文件中加入log打印日志
<settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings>
5.打印结果
==> Preparing: select * from members where 1 = 1 ==> Parameters: <== Columns: id, member_name, pass_word, age <== Row: 1, 张三, 123456, 25 <== Row: 2, 李四, 123456, 25 <== Row: 3, 关云长, 123456, 54 <== Row: 4, 关云长, 123456, 54 <== Total: 4 [Member [id=1, member_name=张三, password=123456, age=25], Member [id=2, member_name=李四, password=123456, age=25], Member [id=3, member_name=关云长, password=123456, age=54], Member [id=4, member_name=关云长, password=123456, age=54]]
条件成立则拼接相应的条件,不成立则不拼接