如果使用JDBC或者其他框架,很多时候你得根据需要去拼接SQL,这是一个麻烦的事情,而MyBatis提供对SQL语句动态的组装能力,而且它只有几个基本的元素,非常简单明了,大量的判断都可以在MyBatis的映射XML文件里面配置,以达到许多我们需要大量代码才能实现的功能,大大减少了我们编写代码的工作量,这体现了MyBatis的灵活性、高度可配置性和可维护性。MyBatis也可以在注解中配置SQL,但是由于注解中配置功能受限,对于复杂的SQL而言可读性很差,所以使用较少。
新增AI编程课程,引领技术教育新趋势
如果使用JDBC或者其他框架,很多时候你得根据需要去拼接SQL,这是一个麻烦的事情,而MyBatis提供对SQL语句动态的组装能力,而且它只有几个基本的元素,非常简单明了,大量的判断都可以在MyBatis的映射XML文件里面配置,以达到许多我们需要大量代码才能实现的功能,大大减少了我们编写代码的工作量,这体现了MyBatis的灵活性、高度可配置性和可维护性。MyBatis也可以在注解中配置SQL,但是由于注解中配置功能受限,对于复杂的SQL而言可读性很差,所以使用较少。
<select id="selectName" parameterType="String" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from `user` <where> <if test="userName!=''"> and user_name = #{userName} </if> </where> </select>
<if>中的test通常判断的条件是不等于Null或者空字符串,除此之外还可以进行比较判断比如大于等于小于等这样的。
二、choose、when、otherwise
<select id="selectName" parameterType="String" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from `user` <choose> <when test="userName!=null and userName!=''"> where userName = #{userName} </when> <otherwise> where sex = #{sex} </otherwise> </choose> </select>
你可以将<choose><when></when><otherwise></otherwise></choose>理解为Java中的if-else或者是if-else if-else
三、trim、where、set
trim+where示例:
<select id="selectName" parameterType="String" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from `user` <trim prefix="where" prefixOverrides="AND |OR"> <if test="userName !=null and userName!=''"> and user_name = #{userName} </if> </trim> </select>
prefix:前缀
prefixoverride:去掉第一个and或者是or
trim+set示例:
update user <trim prefix="set" suffixoverride="," suffix=" where id = #{id} "> <if test="name != null and name.length()>0"> name=#{name} , </if> <if test="gender != null and gender.length()>0"> gender=#{gender} , </if> </trim>
prefix同trim+where的意思是一样,都是前缀。
suffixoverride:去掉最后一个逗号(也可以是其他的标记,就像是上面前缀中的and一样)
suffix:后缀
四、foreach
批量更新示例:
<update id="udpateUserLogoStatu" parameterType="java.util.List"> <foreach collection="users" item="user" index="index" separator=";"> update `user` <set> logo = 1 </set> where logo = #{user.logo} </foreach> &