Mybatis dynamic SQL query and update

Queries are often used to < if > < choose > < when > < otherwise > < trim > tags, and they all support ognl expressions
--|The < if > condition judgment is the same as if in Java, such as

<if test="id!=null and id!=''">

--|< choose > is just like Java's switch with break, which is used with < when > < otherwise >
----|< when > when the condition is met, the splicing is performed, such as

			<when test="custId!=null and custId%2==0" >
				concat(cust_name,'_aa') cust_name
			</when>

----|When all < when > are not satisfied, splice its contents, such as

			<otherwise>
				concat(cust_name,'_bb') cust_name
			</otherwise>

A complete query example configuration:

	<!-- Complex queries, using if choose Label -->
	<select id="getCustsByCust" resultType="com.jv.dynamic.bean.Cust">
		select cust_id,
		<choose>
			<when test="custId!=null and custId%2==0" >
				concat(cust_name,'_aa') cust_name
			</when>
			<otherwise>
				concat(cust_name,'_bb') cust_name
			</otherwise>
		</choose>
		from cust
		<where>
			<!-- ognl Expressions also support&&Wait for the operator, but xml Its escape character is required in
				For example:<if test="custId!=null!=null &amp;&amp; custId!=null!=&quot;&quot;">
				among&amp;Is the representative&Symbol;&quot;For double quotes
				
				Lung metastases are recommended for ease of reading
			-->
			<if test="custId!=null and custId!=''">
				cust_id=#{custId}
			</if>
			<if test="custName!=null and custName!=''">
				and cust_name like #{custName}
			</if>
		</where>
	</select>

In the actual project development, some companies or developers prefer to write "where 1=1" instead of using the < where > tag, and the SQL corresponding to all the subsequent condition judgments starts with "and", which is also handy and flexible.

Why use the < where > tag? Because Mybatis can help us if we write "and" at the beginning, there will be no splicing completion sql, where and column? Name =? The situation. If you put "and" at the end, the < where > tag is useless, but you can use the < trim > tag, for example:

         <trim suffixOverrides="">
            <if test="custId!=null and custId!=''">
				cust_id=#{custId} and
			</if>
			<if test="custName!=null and custName!=''">
				cust_name like #{custName}
			</if>
         </trim>


Update common to < set > tags

<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>

Keywords: Java SQL xml Mybatis

Added by clio-stylers on Sun, 03 May 2020 09:51:47 +0300