1. 程式人生 > 其它 >MyBatis學習筆記(四)—— 動態SQL

MyBatis學習筆記(四)—— 動態SQL

技術標籤:MyBatismybatis

MyBatis學習筆記(四)—— 動態SQL

尚矽谷-MyBatis

https://www.bilibili.com/video/BV1d4411g7tv?p=230


文章目錄

一、if標籤

二、trim標籤

三、foreach標籤

四、choose標籤

五、Set標籤


一、if標籤

動態SQL:簡化SQL語句動態拼串操作。

(1)建表t_teacher

(2)新建Teacher實體類和dao

public class Teacher {
    private Integer id;
    private String name;
    private String course;
    private String address;
    private Date birth;

    public Teacher(Integer id, String name, String course, String address, Date birth) {
        this.id = id;
        this.name = name;
        this.course = course;
        this.address = address;
        this.birth = birth;
    }

    public Teacher() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCourse() {
        return course;
    }

    public void setCourse(String course) {
        this.course = course;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", course='" + course + '\'' +
                ", address='" + address + '\'' +
                ", birth=" + birth +
                '}';
    }
}

public interface TeacherDao {
    public Teacher getTeacherById(Integer id);

    public List<Teacher> getTeacherByCondition(Teacher teacher);
}

(3)編寫全域性配置檔案

dbconfig.properties:

driverclass=com.mysql.cj.jdbc.Driver
jdbcurl=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
username=root
password=root

mybatis.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!--properties屬性:引用外部配置檔案
         resource:從類路徑下開始引用
         url:引用磁碟路徑或網路路徑下的資源
    -->
    <properties resource="dbconfig.properties"/>
    
    <settings>
        <!--開啟延遲載入物件-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--開啟屬性按需載入-->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>

    <!--default預設使用的環境-->
    <environments default="development">
        <!--id是當前環境的唯一標識-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!--配置連線池-->
            <dataSource type="POOLED">
                <!--取出配置檔案中的值-->
                <property name="driver" value="${driverclass}"/>
                <property name="url" value="${jdbcurl}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--mappers(對映器):寫好的sql對映檔案需要使用mappers註冊進來-->
    <mappers>
        <!--resource:在類路徑下找對映檔案
            url:引用磁碟路徑或網路路徑下的對映檔案
            class:直接引用介面的全類名,需要把xml和dao介面放在同目錄下切命名相同
        -->
        <mapper resource="teacherdao.xml"/>
    </mappers>
</configuration>

(4)編寫SQL配置檔案

teacherdao.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">
<!--namespace:名稱空間。寫介面給的全類名,相當於告訴MyBatis這個配置檔案是實現哪個介面的。-->

<mapper namespace="smq.dao.TeacherDao">
    <select id="getTeacherById" resultMap="teacherMap">
        select * from t_teacher where id=#{id}
    </select>

    <select id="getTeacherByCondition" resultMap="teacherMap">
        select * from t_teacher where
        <!--test中編寫判斷條件
            id!=null表示取出傳入的javaBean屬性中的id值判斷其是否為空
        -->
        <if test="id!=null &amp;&amp; name!=''">
            id > #{id}
        </if>
        <if test="name!=null">
            and teacherName like #{name}
        </if>
        <if test="birth!=null">
            and birth_name > #{birth}
        </if>
    </select>

    <resultMap id="teacherMap" type="smq.javabean.Teacher">
        <id property="id" column="id"/>
        <result property="address" column="address"/>
        <result property="course" column="class_name"/>
        <result property="name" column="teacherName"/>
        <result property="birth" column="birth_date"/>
    </resultMap>
</mapper>

(5)測試

public class MyBatisTest {
    SqlSessionFactory sqlSessionFactory;

    //@Test之前執行
    @Before
    public void initSqlSessionFactory() throws IOException {
        //根據全域性配置檔案建立一個SqlSessionFactory
        String resource = "mybatis.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //SqlSessionFactory是SqlSession工廠,負責建立SqlSession物件
        //SqlSession代表和資料庫的一次會話
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    }


    /**
     * @throws IOException
     */
    @Test
    public void testTeacher() throws IOException {
        //initSqlSessionFactory();
        //獲取和資料庫的一次會話
        SqlSession openSession = sqlSessionFactory.openSession();
        //使用SqlSession操作資料庫
        //獲取dao介面的實現
        try {
            TeacherDao teacherDao = openSession.getMapper(TeacherDao.class);
            Teacher teacher = teacherDao.getTeacherById(1);
            System.out.println(teacher);
        }finally {
            openSession.close();
        }
    }

    /**
     * if測試
     * @throws IOException
     */
    @Test
    public void testTeacherIf() throws IOException {
        //initSqlSessionFactory();
        //獲取和資料庫的一次會話
        SqlSession openSession = sqlSessionFactory.openSession();
        //使用SqlSession操作資料庫
        //獲取dao介面的實現
        try {
            TeacherDao teacherDao = openSession.getMapper(TeacherDao.class);
            Teacher teacher = new Teacher();
            teacher.setId(1);
            teacher.setName("%a%");
            List<Teacher> teachers = teacherDao.getTeacherByCondition(teacher);
            System.out.println(teachers);
        }finally {
            openSession.close();
        }
    }
}

二、trim標籤

trim標籤:擷取字串。

  • prefix:字首,為下面的sql整體新增一個字首。
  • prefixOverrides:取出整體字串前多餘的字元。
  • suffix:為整體新增一個字尾。
  • suffixOverrides:取出整體字串後獲取的字尾。
    <select id="getTeacherByCondition" resultMap="teacherMap">
        select * from t_teacher where
        <!--test中編寫判斷條件
            id!=null表示取出傳入的javaBean屬性中的id值判斷其是否為空
        -->
        <!--擷取字串
            prefix:字首,為下面的sql整體新增一個字首
            prefixOverrides:取出整體字串前多餘的字元
            suffix:為整體新增一個字尾
            suffixOverrides:取出整體字串後獲取的字尾
        -->
        <trim prefix="where" prefixOverrides="and" suffix="" suffixOverrides="and">
            <if test="id!=null &amp;&amp; name!=''">
                id > #{id} and
            </if>
            <if test="name!=null">
                and teacherName like #{name} and
            </if>
            <if test="birth!=null">
                and birth_name > #{birth} and
            </if>
        </trim>
    </select>

三、foreach標籤

foreach標籤:遍歷集合。

  • collection="ids":指定要遍歷集合的key。
  • close=")" :以)結束。
  • index="i" :索引。
  • item="id_item":每次遍歷出的元素的變數名,方便引用。
  • open="(" :以(結束。
  • separator=",":每次遍歷元素的分隔符。

(1)TeacherDao新增方法

public List<Teacher> getTeacherByIdIn(@Param("ids") List<Integer> ids);
(2)teacherdao.xml

    <select id="getTeacherByIdIn" resultMap="teacherMap">
         select * from t_teacher where id in
         <!--遍歷集合
             collection="ids":指定要遍歷集合的key
             close=")" :以)結束
             index="i" :索引
             item="id_item":每次遍歷出的元素的變數名,方便引用
             open="(" :以(結束
             separator=",":每次遍歷元素的分隔符
         -->
         <foreach collection="ids" close=")" index="" item="id_item" open="(" separator=",">
            #{id_item}
         </foreach>
    </select>

(3)測試

    /**
     * foreach測試
     * @throws IOException
     */
    @Test
    public void testTeacherForeach() throws IOException {
        //initSqlSessionFactory();
        //獲取和資料庫的一次會話
        SqlSession openSession = sqlSessionFactory.openSession();
        //使用SqlSession操作資料庫
        //獲取dao介面的實現
        try {
            TeacherDao teacherDao = openSession.getMapper(TeacherDao.class);
            List<Teacher> teachers = teacherDao.getTeacherByIdIn(Arrays.asList(1, 2, 3));
            System.out.println(teachers);
        }finally {
            openSession.close();
        }
    }

四、choose標籤

(1)TeacherDao新增方法

public List<Teacher> getTeacherByConditionChoose(Teacher teacher);
(2)teacherdao.xml

   <select id="getTeacherByConditionChoose" resultMap="teacherMap">
         select * from t_teacher
         <where>
             <choose>
                 <when test="id!=null">
                    id=#{id}
                 </when>
                 <when test="name!=null and !name.equals(&quot;&quot;)">
                     teacherName=#{name}
                 </when>
                 <when test="birth!=null">
                     birth_date=#{birth}
                 </when>
                 <otherwise>
                     1=1
                 </otherwise>
             </choose>
         </where>
    </select>

(3)測試

    /**
     * choose測試
     * @throws IOException
     */
    @Test
    public void testTeacherChoose() throws IOException {
        //initSqlSessionFactory();
        //獲取和資料庫的一次會話
        SqlSession openSession = sqlSessionFactory.openSession();
        //使用SqlSession操作資料庫
        //獲取dao介面的實現
        try {
            TeacherDao teacherDao = openSession.getMapper(TeacherDao.class);
            Teacher teacher = new Teacher();
            teacher.setId(1);
            teacher.setName("admin");
            List<Teacher> teachers = teacherDao.getTeacherByConditionChoose(teacher);
            System.out.println(teachers);
        }finally {
            openSession.close();
        }
    }

五、Set標籤

(1)TeacherDao新增方法

public int updateTeacher(Teacher teacher);
(2)teacherdao.xml

    <update id="updateTeacher">
        update t_teacher
        <set>
            <if test="name!=null and !name.equals(&quot;&quot;)">
                teacherName=#{name},
            </if>
            <if test="course!=null and !course.equals(&quot;&quot;)">
                class_name=#{course},
            </if>
            <if test="address!=null and !address.equals(&quot;&quot;)">
                address=#{address},
            </if>
            <if test="birth!=null">
                birth_date=#{birth},
            </if>
        </set>
        <where>
            id=#{id}
        </where>
    </update>

(3)測試

注意:SqlSession openSession = sqlSessionFactory.openSession(true);!!!

    /**
     * set測試
     * @throws IOException
     */
    @Test
    public void testTeacherSet() throws IOException {
        //initSqlSessionFactory();
        //獲取和資料庫的一次會話
        SqlSession openSession = sqlSessionFactory.openSession(true);
        //使用SqlSession操作資料庫
        //獲取dao介面的實現
        try {
            TeacherDao teacherDao = openSession.getMapper(TeacherDao.class);
            Teacher teacher = new Teacher();
            teacher.setId(1);
            teacher.setName("adminupdate");
            Integer id = teacherDao.updateTeacher(teacher);
            System.out.println("更新了" + id + "條資料");
        }finally {
            openSession.close();
        }
    }