Mybatis動態sql語句
阿新 • • 發佈:2021-01-15
在實際開發過程中,我們經常會遇到使用動態sql語句的時候,例如,我們可以根據使用者的id查詢使用者,也可以根據賬號查詢,也可以根據角色查詢。。。。這個時候,如果我們為每一種查詢都編寫一條sql語句,那可以說是撞死的心都有了,而動態sql挽救了我們脆弱的心靈,有效的解決了這個問題。
相信如果大家看完了我Mybatis入門的部落格,對Mybatis應該已經有了初步瞭解,那麼我們人狠話不多,直接上程式碼,也要仔細看註釋哦!
<!--namespace一定要是你介面的全命名哦--> <mapper namespace="com.lsc.mapper.UserMapper"> <!--通過使用者id查詢使用者,id要和介面的方法名一致!, resultType為返回型別,parameterType為引數型別, 記得要寫全包名,我這裡是在配置檔案中配置配置了別名,程式碼如下: <typeAliases> <typeAlias type="com.lsc.domain.User" alias="user"/> </typeAliases>--> <!-- collection為集合型別,open是以什麼開始,close是以什麼結束,item是集合裡我們給取的別名,separator是分隔符, 原本的sql語句應為:select * from user where id in(1,2,3),此處的1,2,3是我要查詢的id集合--> <select id="findUserByIds" resultType="user" parameterType="list"> select * from user <where> <foreach collection="list" open="id in(" close=")" item="id" separator=","> #{id} </foreach> </where> </select> <!--因為我們不知道要根據幾個條件進行查詢,所以此處我們使用if--> <select id="findUserByParm" parameterType="user" resultType="user"> select * from user <where> <if test="id!=0"> and id=#{id} </if> <if test="username!=null"> and sername=#{username} </if> <if test="password!=null"> and password=#{password} </if> </where> </select>