1. 程式人生 > >MyBatis動態SQL之標籤的作用及使用

MyBatis動態SQL之標籤的作用及使用

需求:查詢的時候,帶了帶了哪個條件就用哪個條件進行查詢
類似於Java 的 switch 語句的作用,其中只有一個判斷滿足條件。
可以通過標籤實現:
——————————————————————————————

 <select id="getPerson" resultType="com.fzx.bean.Employee">
        select * from PERSON
        <!--<where>標籤起到了where的關鍵字的作用,同時也起到了去掉每個判斷語句最前面多於的and、or字元的作用。但在本例中,不會存在and、or的字元,所以只是起到了where關鍵字的作用--> 
        <where>
            <!-- 如果帶了id就用id查,如果帶了lastName就用lastName查;只會進入其中一個 -->
            <choose>
                <when test="id!=null">
                    id=#{id}
                </when>
                <when test="lastName!=null">
                    last_name like #{lastName}
                </when>
                <when test="email!=null">
                    email = #{email}
                </when>
                <otherwise>
                    gender = 0
                </otherwise>
            </choose>
        </where>
     </select>