2018-12-04 13:39:14 443浏览
今天扣丁学堂Java培训老师给大家介绍一下关于MyBatis常用写法的详细介绍,首先MyBatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。MyBatis可以使用简单的XML或注解来配置和映射原生信息,将接口和Java的POJOs(PlainOldJavaObjects,普通的Java对象)映射成数据库中的记录。
//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标签
<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动态语句中,where标签会自动去掉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>
以上扣丁学堂Java培训之详解MyBatis常用写法的详细介绍,希望对大家有所帮助,扣丁学堂有专业老师制定的Java学习路线图辅助学员学习,此外还有与时俱进的Java课程体系和Java视频直播课供大家学习,想要学好Java开发技术的小伙伴快快行动吧。扣丁学堂Java技术交流群:670348138。
【关注微信公众号获取更多学习资料】