mybatis 04: mybatis對象分析 + 測試程式碼簡化 + 配置優化

MyBatis對象分析

  • 測試程式碼示例
package com.example.test;

import com.example.pojo.Student;
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.Test;

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

public class TestStudent {
    @Test
    public void testGetAll() throws IOException {
        //使用文件流獲取核心配置文件SqlMapConfig.xml
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //創建SqlSessionFactory工廠
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //取出sqlSession對象
        SqlSession sqlSession = factory.openSession();
        //完成查詢操作
        List<Student> list = sqlSession.selectList("wangxun.getAll");
        list.forEach(System.out::println);
        //關閉sqlSession
        sqlSession.close();
    }

    @Test
    public void testGetById() throws IOException {
        //讀取核心配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //創建SqlSessionFactory對象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //獲取SqlSession
        SqlSession sqlSession = factory.openSession();
        //按主鍵查詢
        Student student = sqlSession.selectOne("wangxun.getById", 3);
        System.out.println(student);
        //關閉SqlSession
        sqlSession.close();
    }

    @Test
    public void testGetByName() throws IOException {
        //讀取核心配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //創建SqlSessionFactory對象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //獲取SqlSession
        SqlSession sqlSession = factory.openSession();
        //按照姓名模糊查詢
        List<Student> students = sqlSession.selectList("wangxun.getByName", "三");
        students.forEach(System.out::println);
        //關閉SqlSession
        sqlSession.close();
    }

    @Test
    public void testInsert() throws IOException {
        //讀取核心配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //創建SqlSessionFactory對象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //獲取SqlSession
        SqlSession sqlSession = factory.openSession();
        //插入數據
        int num = sqlSession.insert("wangxun.insert", new Student("小涵", "[email protected]", 20));
        //切記:在所有的增刪改後,必須手動提交
        sqlSession.commit();
        if (num == 1) {
            System.out.println("插入成功!");
        }else{
            System.out.println("插入失敗!");
        }
        //關閉SqlSession
        sqlSession.close();
    }

    @Test
    public void testDelete() throws IOException {
        //讀取核心配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //創建SqlSessionFactory對象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //獲取SqlSession對象
        SqlSession sqlSession = factory.openSession();
        //執行刪除語句
        int num = sqlSession.delete("wangxun.delete", 5);
        sqlSession.commit();
        if(num == 1){
            System.out.println("刪除成功!");
        }else{
            System.out.println("刪除失敗!");
        }
        //關閉SqlSession
        sqlSession.close();
    }

    @Test
    public void testUpdate() throws IOException {
        //讀取核心配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //創建SqlSessionFactory對象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //獲取SqlSession
        SqlSession sqlSession = factory.openSession();
        //執行更新語句
        int num = sqlSession.update("wangxun.update", new Student(1, "小何", "[email protected]", 20));
        sqlSession.commit();
        if(num == 1){
            System.out.println("更新成功!");
        }else{
            System.out.println("更新失敗!");
        }
        //關閉SqlSession
        sqlSession.close();
    }
}
  • Resources類
    • 解析SqlMapConfig,xml文件,創建出相應的對象
    • InputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
  • SqlSessionFactory介面
    • DefaultSqlSessionFactory是其一個實現類
      • ctrl + h 可以快捷查看本介面的子介面及其實現類
    • SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
  • SqlSession介面
    • DefaultSqlSession是其一個實現類

測試程式碼簡化

  • 簡化後的測試程式碼
package com.example.test;

import com.example.pojo.Student;
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 TestStudent {
    //SqlSession對象
    SqlSession sqlSession;
    
    //獲取SqlSession對象
    @Before
    public void createSqlSession() throws IOException {
        //使用文件流獲取核心配置文件SqlMapConfig.xml
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //創建SqlSessionFactory工廠
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //取出sqlSession對象
        sqlSession = factory.openSession();
    }
    
    //歸還SqlSession對象
    @After
    public void closeSqlSession(){
        sqlSession.close();
    }
    
    
    @Test
    public void testGetAll() throws IOException {
        //完成查詢操作
        List<Student> list = sqlSession.selectList("wangxun.getAll");
        list.forEach(System.out::println);
    }

    @Test
    public void testGetById() throws IOException {
        //按主鍵查詢
        Student student = sqlSession.selectOne("wangxun.getById", 3);
        System.out.println(student);
    }

    @Test
    public void testGetByName() throws IOException {
        //按照姓名模糊查詢
        List<Student> students = sqlSession.selectList("wangxun.getByName", "三");
        students.forEach(System.out::println);
    }

    @Test
    public void testInsert() throws IOException {
        //插入數據
        int num = sqlSession.insert("wangxun.insert", new Student("小涵", "[email protected]", 20));
        //切記:在所有的增刪改後,必須手動提交
        sqlSession.commit();
        if (num == 1) {
            System.out.println("插入成功!");
        }else{
            System.out.println("插入失敗!");
        }
    }

    @Test
    public void testDelete() throws IOException {
        //執行刪除語句
        int num = sqlSession.delete("wangxun.delete", 5);
        sqlSession.commit();
        if(num == 1){
            System.out.println("刪除成功!");
        }else{
            System.out.println("刪除失敗!");
        }
    }

    @Test
    public void testUpdate() throws IOException {
        //執行更新語句
        int num = sqlSession.update("wangxun.update", new Student(1, "小何", "[email protected]", 20));
        sqlSession.commit();
        if(num == 1){
            System.out.println("更新成功!");
        }else{
            System.out.println("更新失敗!");
        }
    }
}

實體類別名註冊

  • 單個實體類起別名
    <!-- 為實體類註冊別名
         注意標籤的出現順序
    -->
    <typeAliases>
        <typeAlias type="com.example.pojo.Student" alias="student"/>
    </typeAliases>
  • 批量為實體類起別名
    <typeAliases>
        <!-- 包下的所有實體類自動起別名(規範):
              別名是實體類類名的駝峰命名法
        -->
        <package name="com.example.pojo"/>
    </typeAliases>


	<!-- 例如:
		com.example.pojo包下有實體類:Studnet
		則使用到該實體類的sql標籤可以如下表示:
	-->
    <select id="getAll" resultType="student">
        select
            id, name, email, age
        from
            student
    </select>

設置日誌輸出

  • 配置示例
    <!-- 設置日誌輸出sql語句底層執行的程式碼-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
  • 測試示例
package com.example.test;

import com.example.pojo.Student;
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 TestStudent {
    //SqlSession對象
    SqlSession sqlSession;

    //獲取SqlSession對象
    @Before
    public void createSqlSession() throws IOException {
        //使用文件流獲取核心配置文件SqlMapConfig.xml
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //創建SqlSessionFactory工廠
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //取出sqlSession對象
        sqlSession = factory.openSession();
    }
    //歸還SqlSession對象
    @After
    public void closeSqlSession(){
        sqlSession.close();
    }


    @Test
    public void testGetAll() throws IOException {
        //完成查詢操作
        List<Student> list = sqlSession.selectList("wangxun.getAll");
        list.forEach(System.out::println);
    }
}

/*
輸出結果的部分:
Checking to see if class com.example.pojo.Student matches criteria [is assignable to Object]
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.

Opening JDBC Connection

Created connection 1806880779.

Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6bb2d00b]

==>  Preparing: select id, name, email, age from student
==> Parameters: 
<==    Columns: id, name, email, age
<==        Row: 1, 小何, [email protected], 20
<==        Row: 2, 李四, [email protected], 21
<==        Row: 3, 王五, [email protected], 22
<==        Row: 4, 趙六, [email protected], 24
<==        Row: 6, 小涵, [email protected], 20
<==      Total: 5
Student{id=1, name='小何', email='[email protected]', age=20}
Student{id=2, name='李四', email='[email protected]', age=21}
Student{id=3, name='王五', email='[email protected]', age=22}
Student{id=4, name='趙六', email='[email protected]', age=24}
Student{id=6, name='小涵', email='[email protected]', age=20}

Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6bb2d00b]

Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6bb2d00b]

Returned connection 1806880779 to pool.

Process finished with exit code 0
*/
Tags: