MyBatis中select条件配置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011393781/article/details/52288589

在mybatis中进行mapper.xml配置时,查询条件有多个,所以要用到<if>标签

<select id="getCashInvoiceByQuery" parameterType="com.dfire.soa.invoice.query.CashInvoiceQuery" resultMap="CashInvoiceMap">
     select *
       from cash_print
    where
        <if test=" null != entityId">
            and entity_id = #{entityId}
        </if>
        <if test=" null != orderId">
            and order_id = #{orderId}
        </if>
        <if test=" null != customerRegisterId">
            and customer_register_id = #{customerRegisterId}
        </if>
       order by create_time desc
        LIMIT #{startPos},#{pageSize}
但这样出现的问题是:每个条件都必须复制,否则就会报错:SQL语法有错误,注意:and是在<if>条件中,这样当满足条件时,才会加上and条件。

这就需要用到<where>标签,因为当所有的查询条件都为空时,就会变成:


select * from cash_print where 所以会报语法错误。


<select id="getCashInvoiceByQuery" parameterType="com.dfire.soa.invoice.query.CashInvoiceQuery" resultMap="CashInvoiceMap">
         select *
           from cash_print
        <where>
            <if test=" null != entityId">
                and entity_id = #{entityId}
            </if>
            <if test=" null != orderId">
                and order_id = #{orderId}
            </if>
            <if test=" null != customerRegisterId">
                and customer_register_id = #{customerRegisterId}
            </if>
        </where>
           order by create_time desc
            LIMIT #{startPos},#{pageSize}



展开阅读全文

没有更多推荐了,返回首页