MyBatis学习笔记(六)动态sql
生活随笔
收集整理的這篇文章主要介紹了
MyBatis学习笔记(六)动态sql
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在一些情況下,如查詢參數(shù)不確定時(shí),需要用到動(dòng)態(tài)sql 例子,根據(jù)動(dòng)態(tài)輸入的查詢條件查詢student. 一.if語(yǔ)句 1.StudentTMapper [html] view plain copy package?com.skymr.mybatis.mappers;?? ?? import?java.util.List;?? import?java.util.Map;?? ?? import?com.skymr.mybatis.model.Student;?? ?? public?interface?StudentTMapper?{?? ?? ????public?List<Student>?searchStudents(Map<String,Object>?map);?? }?? map參數(shù)是查詢條件 2.StudentTMappler.xml [html] view plain copy <?xml?version="1.0"?encoding="UTF-8"??>?? <!DOCTYPE?mapper?PUBLIC?"-//mybatis.org//DTD?Mapper?3.0//EN"?"http://mybatis.org/dtd/mybatis-3-mapper.dtd">?? <!--?namespace:Mapper映射?-->?? <!--?這個(gè)文件感覺(jué)就像StudentMapper接口的實(shí)現(xiàn)一樣,只是從java文件變成了xml文件?? 充當(dāng)了Dao類的功能?? ?-->?? <mapper?namespace="com.skymr.mybatis.mappers.StudentTMapper">?? ?? ????<resultMap?type="Student"?id="stuMap">?? ????????<id?property="id"?column="id"/>?? ????????<result?property="name"?column="name"/>?? ????????<result?property="age"?column="age"/>?? ????????<association?property="address"?column="address_id"?select="com.skymr.mybatis.mappers.AddressMapper.getAddress">?? ????????</association>?? ????????<association?property="grade"?column="grade_id"?select="com.skymr.mybatis.mappers.GradeMapper.getGrade"></association>?? ????</resultMap>?? ????<select?id="searchStudents"?resultMap="stuMap"?parameterType="map">?? ????????select?*?from?mybatis_student?where?1=1?? ????????<if?test="name!=null">?? ????????????and?name?like?#{name}?? ????????</if>?? ????????<if?test="age!=null">?? ????????????and?age=#{age}?? ????????</if>?? ????</select>?? </mapper>??? 3.測(cè)試 [html] view plain copy package?com.skymr.mybatis.service;?? ?? import?java.util.HashMap;?? import?java.util.List;?? import?java.util.Map;?? ?? import?org.apache.ibatis.session.SqlSession;?? import?org.junit.After;?? import?org.junit.Before;?? import?org.junit.Test;?? import?org.slf4j.Logger;?? import?org.slf4j.LoggerFactory;?? ?? import?com.skymr.mybatis.mappers.StudentTMapper;?? import?com.skymr.mybatis.model.Student;?? import?com.skymr.mybatis.util.MybatisUtil;?? ?? public?class?StudentTest4?{?? ?? ????private?Logger?logger?=?LoggerFactory.getLogger(StudentTest4.class);?? ?????? ????private?SqlSession?session;?? ?????? ????@Before?? ????public?void?beforeTest(){?? ????????session?=?MybatisUtil.openSession();?? ????}?? ????@After?? ????public?void?afterTest(){?? ????????session.close();?? ????}?? ?????? ????@Test?? ????public?void?testSearch(){?? ????????logger.info("測(cè)試查詢學(xué)生");?? ????????StudentTMapper?mapper?=?session.getMapper(StudentTMapper.class);?? ????????Map<String,Object>?map?=?new?HashMap<String,?Object>();?? ????????map.put("name",?"%aaa%");?? ????????map.put("age",?111);?? ????????List<Student>?list?=?mapper.searchStudents(map);?? ????????logger.info(list.toString());?? ????}?? ?????? }?? 二.choose,when ,otherwise [html] view plain copy Sometimes?we?don’t?want?all?of?the?conditionals?to?apply,?instead?we?want?to?choose?only?one?case?? among?many?options.?Similar?to?a?switch?statement?in?Java,?MyBatis?offers?a?choose?element.?? Let’s?use?the?example?above,?but?now?let’s?search?only?on?title?if?one?is?provided,?then?only?by?author?? if?one?is?provided.?If?neither?is?provided,?let’s?only?return?featured?blogs?(perhaps?a?strategically?list?? selected?by?administrators,?instead?of?returning?a?huge?meaningless?list?of?random?blogs).?? 有些時(shí)候我們不想所有的條件都使用到,只想在所有條件中選擇一個(gè)條件.與java的switch語(yǔ)種相似,Mybatis提供了一個(gè)元素.讓我們做個(gè)例子. [html] view plain copy <select?id="findActiveBlogLike"?? ?????resultType="Blog">?? ??SELECT?*?FROM?BLOG?WHERE?state?=?‘ACTIVE’?? ??<choose>?? ????<when?test="title?!=?null">?? ??????AND?title?like?#{title}?? ????</when>?? ????<when?test="author?!=?null?and?author.name?!=?null">?? ??????AND?author_name?like?#{author.name}?? ????</when>?? ????<otherwise>?? ??????AND?featured?=?1?? ????</otherwise>?? ??</choose>?? </select>?? 上面的例子是引用Mybatis文檔. 自己的例子: [html] view plain copy <select?id="searchStudents2"?resultMap="stuMap"?parameterType="map">?? ????select?*?from?mybatis_student?where?1=1?? ????<choose>?? ????????<when?test="searchBy=='name'">?? ????????????and?name?like?#{name}?? ????????</when>?? ????????<when?test="searchBy=='gradeId'">?? ????????????and?grade_id=#{gradeId}?? ????????</when>?? ????????<otherwise>?? ????????????and?age=#{age}?? ????????</otherwise>?? ????</choose>?? </select>?? 三.trim, where, set元素 1.當(dāng)沒(méi)有條件時(shí),有可能會(huì)生成這樣的sql [html] view plain copy SELECT?*?FROM?BLOG?? WHERE?? 如果不在后邊加入 1=1,則應(yīng)該加上where標(biāo)簽 [html] view plain copy <select?id="findActiveBlogLike"?? ?????resultType="Blog">?? ??SELECT?*?FROM?BLOG?? ??<where>?? ??????<if?test="state?!=?null">?? ????????state?=?#{state}?? ??????</if>?? ??</where>?? </select>?? 改成這樣就可以避免以上情況. 2.還有這種情況 [html] view plain copy SELECT?*?FROM?BLOG?? WHERE?? AND?title?like?‘someTitle’?? 需要去年多余的and /or [html] view plain copy <select?id="searchStudents3"?resultMap="stuMap"?parameterType="map">?? ????select?*?from?mybatis_student??? ????<trim?prefix="WHERE"?prefixOverrides="AND|OR">?? ????????<if?test="name!=null">?? ????????????and?name?like?#{name}?? ????????</if>?? ????????<if?test="age!=null">?? ????????????and?age=#{age}?? ????????</if>?? ????</trim>?? </select>?? 同樣,update set語(yǔ)句也會(huì)出現(xiàn)多余的","的問(wèn)題 [html] view plain copy <update?id="updateAuthorIfNecessary">?? ??update?Author?? ????<set>?? ??????<if?test="username?!=?null">username=#{username},</if>?? ??????<if?test="password?!=?null">password=#{password},</if>?? ??????<if?test="email?!=?null">email=#{email},</if>?? ??????<if?test="bio?!=?null">bio=#{bio}</if>?? ????</set>?? ??where?id=#{id}?? </update>?? 也可以使用trim修改 [html] view plain copy <update?id="updateAuthorIfNecessary">?? ??update?Author?? ????<trim?prefix="SET"?suffixOverrides=",">?? ??????<if?test="username?!=?null">username=#{username},</if>?? ??????<if?test="password?!=?null">password=#{password},</if>?? ??????<if?test="email?!=?null">email=#{email},</if>?? ??????<if?test="bio?!=?null">bio=#{bio}</if>?? ????</trim>?? ??where?id=#{id}?? </update>?? 四.foreach元素 這是一個(gè)非常有用的動(dòng)態(tài)sql元素,用來(lái)遍歷集合,常應(yīng)用于IN語(yǔ)句中,例: [html] view plain copy IN?condition.?For?example:?? <select?id="selectPostIn"?resultType="domain.blog.Post">?? ??SELECT?*?? ??FROM?POST?P?? ??WHERE?ID?in?? ??<foreach?item="item"?index="index"?collection="list"?? ??????open="("?separator=","?close=")">?? ????????#{item}?? ??</foreach>?? </select>?? foreach元素非常強(qiáng)大,它允許你指定一個(gè)集合,聲明item和index變量,在元素內(nèi)部使用.生成有"開(kāi)始/結(jié)尾/分隔符"的字符串,這個(gè)元素非常智能,它不會(huì)不小心添加額外的分隔符. 記住,你可以把一個(gè)List實(shí)例或者一個(gè)數(shù)組當(dāng)作參數(shù)傳遞到MyBatis.當(dāng)你這樣做了,MyBatis會(huì)自動(dòng)放到一個(gè)Map里.List實(shí)例會(huì)以"list"作為Key值,數(shù)組實(shí)例會(huì)以"array"作為Key值. foreach元素的屬性主要有 item,index,collection,open,separator,close。 item表示集合中每一個(gè)元素進(jìn)行迭代時(shí)的別名. index指 定一個(gè)名字,用于表示在迭代過(guò)程中,每次迭代到的位置. open表示該語(yǔ)句以什么開(kāi)始,separator表示在每次進(jìn)行迭代之間以什么符號(hào)作為分隔 符. close表示以什么結(jié)束. 上面的例子生成的sql相當(dāng)于 SELECT * FROM POST P WHERE ID in (?,?,?)
轉(zhuǎn)載于:https://www.cnblogs.com/bkyliufeng/p/6291777.html
總結(jié)
以上是生活随笔為你收集整理的MyBatis学习笔记(六)动态sql的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Angular2 - Starter -
- 下一篇: ZOJ3163【思维题】