MyBatis dynamic SQL practical tutorial

1. What is MyBatis dynamic sql?

Dynamic SQL is one of the powerful features of MyBatis. In JDBC or other similar frameworks, developers often need to manually splice SQL statements. Splicing SQL statements based on different conditions is an extremely painful task. For example, make sure to add necessary spaces when concatenating, and be careful to remove the comma from the last column name in the list. Dynamic SQL solves this problem and can dynamically build queries based on the scenario.

Dynamic SQL (code that is executed dynamically) is generally a block of SQL statements that are dynamically combined based on user input or external conditions. Dynamic SQL can flexibly exert the powerful functions of SQL and conveniently solve some problems that are difficult to solve by other methods. I believe that anyone who has used dynamic SQL can appreciate the convenience it brings. However, dynamic SQL is sometimes not as good as static SQL in terms of execution performance (efficiency), and if used improperly, there are often hidden dangers in security (SQL injection attacks). ).

1.What does Mybatis dynamic sql do?

Mybatis dynamic sql allows us to write dynamic sql in the form of tags in the Xml mapping file to complete the functions of logical judgment and dynamic splicing of sql.

2.What are the 9 dynamic sql tags in Mybatis?

picture

3. How does dynamic sql execute?

The principle is: use OGNL to calculate the value of the expression from the sql parameter object, and dynamically splice the sql according to the value of the expression to complete the function of dynamic sql.

Two, MyBatis label

1.if tag: conditional judgment

MyBatis if is similar to the if statement in Java and is the most commonly used judgment statement in MyBatis. Using if tags can save a lot of work in splicing SQL and focus on XML maintenance.

1) Do not use dynamic sql

<select id="selectUserByUsernameAndSex"
        resultType="user" parameterType="com.ys.po.User">
    <!-- 这里和普通的sql 查询语句差不多,对于只有一个参数,后面的 #{id}表示占位符,里面          不一定要写id,
         写啥都可以,但是不要空着,如果有多个参数则必须写pojo类里面的属性 -->
    select * from user where username=#{username} and sex=#{sex}
</select>

The if statement is simple to use and is often used in conjunction with the test attribute. The syntax is as follows:

<if test="判断条件">    SQL语句</if>

2) Use dynamic sql

In the above query statement, we can find that if  #{username} it is empty, then the query result is also empty. How to solve this problem? Use if to judge. Multiple if statements can be used at the same time.

The following statements indicate that fuzzy queries can be performed based on the website name (name) or URL (url). If you do not enter a name or URL, all site records are returned. However, if you pass any parameter, it will return records matching the given parameters.

<select id="selectAllWebsite" resultMap="myResult">  
    select id,name,url from website 
    where 1=1    
   <if test="name != null">        
       AND name like #{name}   
   </if>    
   <if test="url!= null">        
       AND url like #{url}    
   </if>
</select>

2.where+if tag

Where and if can be used at the same time to query and fuzzy query

Note that <if>after failure,  <where> the keyword will only remove the and in front of the library table field assignment, and will not remove the and keyword after the statement. That is, note that only the  first and keyword in the statement <where> will be removed . <if>So the following form is not advisable

<select id="findQuery" resultType="Student">
    <include refid="selectvp"/>
    <where>
        <if test="sacc != null">
            sacc like concat('%' #{sacc} '%')
        </if>
        <if test="sname != null">
            AND sname like concat('%' #{sname} '%')
        </if>
        <if test="sex != null">
            AND sex=#{sex}
        </if>
        <if test="phone != null">
            AND phone=#{phone}
        </if>
    </where>
</select>

The "where" tag will know that if the tag it contains has a return value, it will insert a 'where'. In addition, if the content returned by the tag starts with AND or OR, it will be eliminated.

3.set label

set can be used to modify

<update id="upd">
    update student
    <set>
        <if test="sname != null">sname=#{sname},</if>
        <if test="spwd != null">spwd=#{spwd},</if>
        <if test="sex != null">sex=#{sex},</if>
        <if test="phone != null">phone=#{phone}</if>
    sid=#{sid}
    </set>
    where sid=#{sid}
</update>

4.choose(when,otherwise) statement

Sometimes, we don’t want to use all the query conditions, but only want to select one of them. As long as one of the query conditions is satisfied, using the choose tag can solve such problems, similar to Java’s switch statement.

<select id="selectUserByChoose" resultType="com.ys.po.User" parameterType="com.ys.po.User">
      select * from user
      <where>
          <choose>
              <when test="id !='' and id != null">
                  id=#{id}
              </when>
              <when test="username !='' and username != null">
                  and username=#{username}
              </when>
              <otherwise>
                  and sex=#{sex}
              </otherwise>
          </choose>
      </where>
  </select>

In other words, we have three conditions here, id, username, and sex. We can only choose one as the query condition.

  • If id is not empty, then the query statement is:select * from user where id=?

  • If id is empty, then check whether username is empty. If not, then the statement is select * from user where username=?;

  • If username is empty, then the query statement is select * from user where sex=?

5.trim

The trim mark is a formatting mark that can complete the function of set or where mark.

①. Use trim to rewrite the if+where statement in the second point above.

<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
    select * from user
    <!-- <where>
        <if test="username != null">
           username=#{username}
        </if>
         
        <if test="username != null">
           and sex=#{sex}
        </if>
    </where>  -->
    <trim prefix="where" prefixOverrides="and | or">
        <if test="username != null">
           and username=#{username}
        </if>
        <if test="sex != null">
           and sex=#{sex}
        </if>
    </trim>
</select>
  • prefix: prefix

  • prefixoverride: remove the first and or or

②. Use trim to rewrite the if+set statement in the third point above.

<!-- 根据 id 更新 user 表的数据 -->
<update id="updateUserById" parameterType="com.ys.po.User">
    update user u
        <!-- <set>
            <if test="username != null and username != ''">
                u.username = #{username},
            </if>
            <if test="sex != null and sex != ''">
                u.sex = #{sex}
            </if>
        </set> -->
        <trim prefix="set" suffixOverrides=",">
            <if test="username != null and username != ''">
                u.username = #{username},
            </if>
            <if test="sex != null and sex != ''">
                u.sex = #{sex},
            </if>
        </trim>
     
     where id=#{id}
</update>
  • suffix: suffix

  • suffixoverride: remove the last comma (it can also be other tags, just like the and in the above prefix)

③. Use trim+if at the same time to add

<insert id="add">
    insert  into student
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="sname != null">sname,</if>
        <if test="spwd != null">spwd,</if>
        <if test="sex != null">sex,</if>
        <if test="phone != null">phone,</if>
    </trim>

    <trim prefix="values (" suffix=")"  suffixOverrides=",">
        <if test="sname != null">#{sname},</if>
        <if test="spwd != null">#{spwd},</if>
        <if test="sex != null">#{sex},</if>
        <if test="phone != null">#{phone}</if>
    </trim>

</insert>

6. MyBatis foreach tag

foreach is used to traverse a collection, which is very similar to the function in Java. Usually handles the in statement in SQL.

The foreach element is very powerful. It allows you to specify a collection and declare collection items and index variables that can be used within the element body. It also allows you to specify starting and ending strings and separators between iterations of collection items. This element also does not mistakenly add extra delimiters

You can pass any iterable object (such as List, Set, etc.), Map object, or array object as a collection parameter to foreach. When using an iterable object or array, index is the serial number of the current iteration, and the value of item is the element obtained in this iteration. When using a Map object (or a collection of Map.Entry objects), index is the key and item is the value.

//批量查询
<select id="findAll" resultType="Student" parameterType="Integer">
    <include refid="selectvp"/> WHERE sid in
    <foreach item="ids" collection="array"  open="(" separator="," close=")">
        #{ids}
    </foreach>
</select>
//批量删除
<delete id="del"  parameterType="Integer">
    delete  from  student  where  sid in
    <foreach item="ids" collection="array"  open="(" separator="," close=")">
        #{ids}
    </foreach>
</delete>
Integration case

xml

<?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">
<mapper namespace="com.yzx.mapper.StuMapper">
    <sql id="selectvp">
        select  *  from  student
    </sql>
    
    <select id="find" resultType="Student">
        <include refid="selectvp"/>
    </select>

    <select id="findbyid"  resultType="student">
        <include refid="selectvp"/>
        WHERE 1=1
        <if test="sid != null">
            AND sid like #{sid}
        </if>
    </select>

        <select id="findQuery" resultType="Student">
            <include refid="selectvp"/>
            <where>
                <if test="sacc != null">
                    sacc like concat('%' #{sacc} '%')
                </if>
                <if test="sname != null">
                    AND sname like concat('%' #{sname} '%')
                </if>
                <if test="sex != null">
                    AND sex=#{sex}
                </if>
                <if test="phone != null">
                    AND phone=#{phone}
                </if>
            </where>
        </select>

    <update id="upd">
        update student
        <set>
            <if test="sname != null">sname=#{sname},</if>
            <if test="spwd != null">spwd=#{spwd},</if>
            <if test="sex != null">sex=#{sex},</if>
            <if test="phone != null">phone=#{phone}</if>
        sid=#{sid}
        </set>
        where sid=#{sid}
    </update>

    <insert id="add">
        insert  into student
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="sname != null">sname,</if>
            <if test="spwd != null">spwd,</if>
            <if test="sex != null">sex,</if>
            <if test="phone != null">phone,</if>
        </trim>

        <trim prefix="values (" suffix=")"  suffixOverrides=",">
            <if test="sname != null">#{sname},</if>
            <if test="spwd != null">#{spwd},</if>
            <if test="sex != null">#{sex},</if>
            <if test="phone != null">#{phone}</if>
        </trim>

    </insert>
    <select id="findAll" resultType="Student" parameterType="Integer">
        <include refid="selectvp"/> WHERE sid in
        <foreach item="ids" collection="array"  open="(" separator="," close=")">
            #{ids}
        </foreach>
    </select>

    <delete id="del"  parameterType="Integer">
        delete  from  student  where  sid in
        <foreach item="ids" collection="array"  open="(" separator="," close=")">
            #{ids}
        </foreach>
    </delete>



</mapper>

Test class:

package com.yzx.test;

import com.yzx.entity.Student;
import com.yzx.mapper.StuMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class StuTest {
    SqlSession sqlSession=null;
    InputStream is=null;

    @Before
    public   void  before() throws IOException {
        //1.读取核心配置文件
        is= Resources.getResourceAsStream("sqlMapperConfig.xml");
        //2.拿到工厂构建类
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
        //3.拿到具体工厂
        SqlSessionFactory build=sqlSessionFactoryBuilder.build(is);
        //4.拿到session
        sqlSession = build.openSession();
    }

    @After
    public  void  after(){
        //7,提交事务
        sqlSession.commit();
        //8.关闭资源
        sqlSession.close();
        if(is!=null){
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        };
    }

    //查询所有
    @Test
    public  void  find(){
        //5.获取具体的mapper接口
        StuMapper mapper=sqlSession.getMapper(StuMapper.class);
        //6.调用执行
        List<Student> list=mapper.find();
        list.forEach(a-> System.out.println(a));
    }
    //查询单个
    @Test
    public  void  findbyid(){

        StuMapper mapper=sqlSession.getMapper(StuMapper.class);
        List<Student> list=mapper.findbyid(2);
        list.forEach(a-> System.out.println(a));
    }
    //模糊查询
    @Test
    public  void  findQuery(){

        StuMapper mapper=sqlSession.getMapper(StuMapper.class);

        Student  stu=new Student();
        stu.setSname("小");
        stu.setSex("男");
        List<Student> list=mapper.findQuery(stu);
        list.forEach(a-> System.out.println(a));
    }
    //修改
    @Test
    public  void  upd(){

        StuMapper mapper=sqlSession.getMapper(StuMapper.class);

        Student  stu=new Student();
        stu.setSid(3);
        stu.setSname("小若");
        stu.setSex("人妖");
        int i=mapper.upd(stu);
        System.out.println("修改了"+i+"条数据"+"  "+stu.toString());

    }
    //添加
    @Test
    public  void  add(){

        StuMapper mapper=sqlSession.getMapper(StuMapper.class);

        Student  stu=new Student();
        stu.setSname("小贺");
        stu.setSex("男");
        stu.setPhone("99999999");
        int i=mapper.add(stu);
        System.out.println("添加了"+i+"条数据"+"  "+stu.toString());

    }

    //批量操作
    @Test
    public  void  findAll(){

        StuMapper mapper=sqlSession.getMapper(StuMapper.class);
        Integer[] i={1,2,3,4};
        List<Student> list=mapper.findAll(i);
        list.forEach(a-> System.out.println(a));
    }
    //批量操作

    //批量删除
    @Test
    public  void  del(){
        StuMapper mapper=sqlSession.getMapper(StuMapper.class);
        Integer[] i={1,2,3,4};
        int i1=mapper.del(i);
        System.out.println("删除了"+i1+"条数据");
    }
}

7.sql

In actual development, we will encounter many identical SQLs, such as filtering based on a certain condition. This filtering can be used in many places. We can extract it into a common part, which is also convenient to modify. Once an error occurs, You only need to change this one part and it will take effect everywhere. <sql>This tag is used at this time.

When the query fields or query conditions of multiple types of query statements are the same, they can be defined as constants for easy calling. <select>The sql statement can also be decomposed for a clear structure.

<sql id="selectvp">
    select  *  from  student
</sql>

8.include

This tag <sql>is a perfect match and is symbiotic. include is used to reference the constants defined by the sql tag. For example, refer to the constant defined by the above sql tag

The refid attribute is <sql>the id value (unique identification) in the specified tag.

<select id="findbyid"  resultType="student">
    <include refid="selectvp"/>
    WHERE 1=1
    <if test="sid != null">
        AND sid like #{sid}
    </if>
</select>

9. How to reference SQL fragments in other XML

For example, you com.xxx.dao.xxMapperdefine a SQL fragment in this Mapper's XML as follows:

<sql id="Base_Column_List"> ID,MAJOR,BIRTHDAY,AGE,NAME,HOBBY</sql>

At this point I com.xxx.dao.PatinetMapperneed to quote it in the XML file, as follows:

<include refid="com.xxx.dao.xxMapper.Base_Column_List"></include>

3. MyBatis related query

1.MyBatis one-to-many association query

<!--一对多-->
<resultMap id="myStudent1" type="student1">
    <id property="sid" column="sid"/>
    <result property="sname" column="sname"/>
    <result property="sex" column="sex"/>
    <result property="sage" column="sage"/>
    <collection property="list" ofType="teacher">
        <id property="tid" column="tid"/>
        <result property="tname" column="tname"/>
        <result property="tage" column="tage"/>
    </collection>
</resultMap>

<!--一对多-->
<select id="find1" resultMap="myStudent1">
    select  *  from  student1  s  left  join  teacher  t  on s.sid=t.sid
</select>

2.MyBatis many-to-one related query

<!--多对一-->
<resultMap id="myTeacher" type="teacher">
    <id property="tid" column="tid"/>
    <result property="tname" column="tname"/>
    <result property="tage" column="tage"/>
    <association property="student1" javaType="Student1">
        <id property="sid" column="sid"/>
        <result property="sname" column="sname"/>
        <result property="sex" column="sex"/>
        <result property="sage" column="sage"/>
    </association>
</resultMap>


<!--多对一-->
<select id="find2" resultMap="myTeacher">
select  *  from  teacher  t right join student1 s on  t.sid=s.sid
</select>

3.MyBatis many-to-many related query

<!--多对多 以谁为主表查询的时候,主表约等于1的一方,另一方相当于多的一方-->
<select id="find3" resultMap="myStudent1">
    select  *  from  student1 s  left join relevance r on  s.sid=r.sid  left join teacher t on  r.tid=t.tid
</select>

Guess you like

Origin blog.csdn.net/WXF_Sir/article/details/132715115