2018-12-04 13:39:14 1231瀏覽
今天扣丁學(xué)堂Java培訓(xùn)老師給大家介紹一下關(guān)于MyBatis常用寫法的詳細(xì)介紹,首先MyBatis是一款優(yōu)秀的持久層框架,它支持定制化SQL、存儲過程以及高級映射。MyBatis避免了幾乎所有的JDBC代碼和手動設(shè)置參數(shù)以及獲取結(jié)果集。MyBatis可以使用簡單的XML或注解來配置和映射原生信息,將接口和Java的POJOs(PlainOldJavaObjects,普通的Java對象)映射成數(shù)據(jù)庫中的記錄。
//mapper中需要傳遞一個容器 public List<User> queryByIdList(List<Integer> userIdList); <select id="queryByIdList" resultMap="BaseResultMap" parameterType="map"> SELECT * FROM user WHERE userId IN <foreach collection="userIdList" item="id" index="index" open="(" close=")" separator=","> #{id} </foreach> </select>2、concat模糊查詢
//模糊查詢使用concat拼接sql <select id="queryByName" resultMap="BaseResultMap" paramterType"string"> SELECT * FROM user <where> <if test="name != null"> name like concat('%', concat(#{name}, '%')) </if> </where> </select>3、if+where標(biāo)簽
<select id="getUserList" resultMap="BaseResultMap" paramterType="com.demo.User"> SELECT * FROM user <where> <if test="userId !=null and userId!= ''"> userId= #{userId} </if> <if test="name !=null and name!= ''"> AND name= #{name} </if> <if phone="userId !=null and phone!= ''"> AND phone= #{phone} </if> </where> </select>where動態(tài)語句中,where標(biāo)簽會自動去掉AND或OR。防止WHEREAND錯誤。
<update id="updateUser" paramterType="com.demo.User"> UPDATE user <set> <if test=" name != null and name != ''"> name = #{name}, </if> <if test=" phone != null and phone != ''"> phone = #{phone}, </if> </set> WHERE userId = #{userId} </update>
<select id="getUserList" resultMap="BaseResultMap" paramterType="com.demo.User"> SELECT * FROM user <trim prefix="WHERE" prefixOverrides="AND|OR"> <if test="userId !=null and userId!= ''"> userId= #{userId} </if> <if test="name !=null and name!= ''"> AND name= #{name} </if> <if phone="userId !=null and phone!= ''"> AND phone= #{phone} </if> </trim> </select> <update id="updateUser" paramterType="com.demo.User"> UPDATE user <trim prefix="SET" suffixOverrides=","> <if test=" name != null and name != ''"> name = #{name}, </if> <if test=" phone != null and phone != ''"> phone = #{phone}, </if> </trim> WHERE userId = #{userId} </update>
<select id="selectCustomerByCustNameAndType" parameterType="map" resultMap="BaseResultMap"> SELECT * FROM user <choose> <when test="Utype == 'name'"> WHERE name = #{name} </when> <when test="Utype == 'phone'"> WHERE phone= #{phone} </when> <when test="Utype == 'email'"> WHERE email= #{email} </when> <otherwise> WHERE name = #{name} </otherwise> </choose> </select>
以上扣丁學(xué)堂Java培訓(xùn)之詳解MyBatis常用寫法的詳細(xì)介紹,希望對大家有所幫助,扣丁學(xué)堂有專業(yè)老師制定的Java學(xué)習(xí)路線圖輔助學(xué)員學(xué)習(xí),此外還有與時俱進(jìn)的Java課程體系和Java視頻直播課供大家學(xué)習(xí),想要學(xué)好Java開發(fā)技術(shù)的小伙伴快快行動吧??鄱W(xué)堂Java技術(shù)交流群:670348138。
【關(guān)注微信公眾號獲取更多學(xué)習(xí)資料】