码迷,mamicode.com
首页 > 数据库 > 详细

Mybatis之动态SQL&OGNL表达式

时间:2018-01-22 00:02:37      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:gimp   tty   space   ssi   log打印   color   mic   where   member   

1.接口

public interface MemberMapperDynamicSQL {

    public List<Members> selectMembersByIf(Members member);

}

2.配置文件

<mapper namespace="com.dao.MemberMapperDynamicSQL">

    <!-- 
        OGNL表达式
        &的转义字符为 &amp;
        ‘的转义字符为 &quot;
     -->
    <select id="selectMembersByIf" resultType="members">
    
        select * from members where 1 = 1
        
        <if test="id != null &amp;&amp; id != &quot;&quot;">
            and id = #{id}
        </if>
        
        <if test="member_name != null &amp;&amp; member_name != &quot;&quot;">
            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]]

条件成立则拼接相应的条件,不成立则不拼接

Mybatis之动态SQL&OGNL表达式

标签:gimp   tty   space   ssi   log打印   color   mic   where   member   

原文地址:https://www.cnblogs.com/zhangjianbing/p/8325745.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!