在 MyBatis 的 SQL映射文件中,有時候須要根據一些查詢條件,來選擇不一樣的SQL語句,若是每個場景都重寫SQL,很顯然效率沒有很高,而 MyBatis 的動態SQL很好的解決了這種問題,根據條件動態的處理 SQL, 特別簡單的說就是,寫一次SQL,可是根據分支等的跳轉,在多個場景下也可使用,例如:java
<where>
標籤包含<where>
可使用 <if test="....">
分條件進行處理,實現動態<foreach>
遍歷標籤放到後面代碼中具體說在此以外,動態SQL同時結局了,在原生 JDBC 中須要拼接SQL語句時因爲書寫問題,而致使報錯sql
/** * 根據條件查詢 * @return */ List<User> findUserByCondition(User user);
<select id="findUserByCondition" resultType="cn.ideal.domain.User" parameterType="cn.ideal.domain.User"> select * from user <where> <if test="username != null"> and username = #{username} </if> <if test="gender != null"> and gender = #{gender} </if> </where> </select>
注意:在SQL中,「and」 用來拼接已有一個或多個查詢條件的語句,當此語句爲第一個查詢條件的時候,會由於 <where>
的存在屏蔽第一個 「and」微信
/** * 根據條件查詢 * @throws Exception */ @Test public void testFindByCondition() throws Exception{ User user = new User(); user.setUsername("湯姆"); user.setGender("女"); List<User> users = userMapper.findUserByCondition(user); for (User u : users){ System.out.println(u); }
有一些語句,在咱們的程序中,使用的頻率特別高,這個時候,咱們也能夠對其進行,單獨的配置,而後達到複用的效果app
首先,咱們須要對其進行簡單的聲明dom
<sql id="xxxxx"> <!-- 複用的SQL --> </sql>
在須要引用的地方,咱們能夠這樣引用ide
<where> include refid="xxxxx"></include> <!-- 可能還用引用別的 --> </where>
提出這樣一種需求,在用戶中查詢尋多個id,例如(12,16,17)咱們能夠這樣寫SQLui
select * from user where id=12 or id=16 or id=17
或者這樣idea
select * from user where id in (12,16,17)
而這種狀況下,咱們須要向SQL中傳遞一個數據或者List類型的參數,而後使用 <foreach>
標籤去遍歷而後解析spa
/** * 根據QueryUserVo中提供的id集合,查詢用戶信息 * @param vo * @return */ List<User> findUserInIds(QueryUserVo vo);
<select id="findUserInIds" resultType="cn.ideal.domain.UserInstance" parameterType="cn.ideal.domain.QueryUserVo"> select * from user <where> <if test="ids != null and ids.size() > 0"> <foreach collection="ids" open="and id in (" close=")" item="uid" separator=","> #{uid} </foreach> </if> </where> </select>
解釋一下code
本例中,我哦們使用了 select * from user where id in (12,16,17)
這種形式,若是想使用 or那種形式,只須要修改拼接格式就能夠了
/** * 根據QueryUserVo中提供的id集合,查詢用戶信息 * @throws Exception */ @Test public void testfindUserInIds() throws Exception{ QueryUserVo vo = new QueryUserVo(); List<Integer> list = new ArrayList<Integer>(); list.add(12); list.add(16); list.add(17); vo.setIds(list); List<User> users = userMapper.findUserInIds(vo); for (User u : users){ System.out.println(u); } }
若是文章中有什麼不足,歡迎你們留言交流,感謝朋友們的支持!
若是能幫到你的話,那就來關注我吧!若是您更喜歡微信文章的閱讀方式,能夠關注個人公衆號
在這裏的咱們素不相識,卻都在爲了本身的夢而努力 ❤一個堅持推送原創開發技術文章的公衆號:理想二旬不止