Mybatis(2)---insert statement, main class introduction, mybatis dynamic agent, mybatis tool class

One, Mybatis executes the insert statement

1.sql mapping file

<?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="HelloMybatis.TestDao">
    <!--
        insert:插入语句
    -->
    <insert id="insertTest">
        <!--这里的#{id}代表传进来对象的属性值-->
        insert into t_test values (#{id},#{name});
    </insert>
</mapper>

2. Interface file

import java.util.List;

//定义操作test表的接口
public interface TestDao
{
    
    
    //插入数据的方法
    //参数test表示要插入数据库的数据
    //返回值int表示执行insert语句后影响数据库的行数
    public int insertTest(Test test);
}

3. The Test class used to save a column of the database

package HelloMybatis;

//用于保存t_test表中一列数据的类
public class Test
{
    
    
    private Integer id;
    private String name;

    public Integer getId() {
    
    
        return id;
    }

    public String getName() {
    
    
        return name;
    }

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

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

    public String toString() {
    
    
        return "Test{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

4. Test class under test folder

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 java.io.InputStream;
import java.util.List;

public class TestInsert
{
    
    
    //测试方法,测试insert语句的功能
    @org.junit.Test
    public void testInsert() throws Exception
    {
    
    
        //访问mybatis读取t_test中的数据
        //1.定义mybatis主配置文件的名称,从类路径的根开始(target/classes之后的)
        String config = "mybatis.xml";
        //2.读取这个config表示的文件
        InputStream in = Resources.getResourceAsStream(config);
        //3.创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //4.创建SqlSessionFactory对象
        SqlSessionFactory factory = builder.build(in);
        //5.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //6.指定要执行的sql语句的标识
        //sql映射文件中的namespace+"."+标签的id值
        String sqlId = "HelloMybatis.TestDao" + "." + "insertTest";
        //7.执行sql语句,通过sqlId找到语句
        Test t = new Test();
        t.setId(1003);
        t.setName("王五");
        int nums = sqlSession.insert(sqlId, t);
        //提交事务
        //mybatis默认不提交事务,只有提交事务后才会真正插入数据
        sqlSession.commit();
        //8.输出结果
        System.out.println("插入数据库的行数为:" + nums);
        //9.关闭sqlSession对象
        sqlSession.close();
    }
}

2. Introduction of main categories

1.Resources

Resources is a class in mybatis, responsible for reading the main configuration file

InputStream in = Resources.getResourceAsStream(“xxx.xml”);

2.SqlSessionFactoryBuilder

SqlSessionFactoryBuilder, used to create SqlSessionFactory objects, used to create SqlSessionFactory objects

SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);

3.SqlSessionFactory

(1) SqlSessionFactory is a heavyweight object
. It takes a long time for the program to create this object and uses more resources. Only one is needed in the whole project
(2) SqlSessionFactory is an interface, and one of its implementation classes is DefaultSqlSessionFactory
(3) The role of SqlSessionFactory: get SqlSession object

SqlSession sqlSession = factory.openSession();

openSession() method:

(1) openSession(): No parameters, sqlSession for non-auto-commit transactions is obtained

(2) openSession(boolean): openSession(true), get the sqlSession of the auto-commit transaction
openSession(false), get the sqlSession of the non-auto-commit transaction

4.SqlSession

SqlSession is an interface that defines many methods of operating transactions.
For example: selectOne(), selectList(), insert(), update(), delete(), commit(), rollback()
The implementation class of the SqlSession interface:
Used by DefaultSqlSession Requirements: Since the SqlSession object is not thread-safe, you need to use the openSession() method to obtain the SqlSession object before executing the sql statement, and you need to close it after executing the sql statement (execute the close method).
This operation is required to ensure thread safety

Three, dynamic agent in Mybatis

Dynamic proxy not used

import org.junit.Test;

import java.util.List;

public class TestMybatis
{
    
    
    @Test
    public void testSelectTests()
    {
    
    
        /**
         * 方法:List<customDAO.Test> tests = test.selectTests();的调用
         * 1,dao对象,类型是TestDao,全限定名称是:HelloMybatis.TestDao
         *    全限定名称和namespace是一样的
         *
         * 2.方法名称:selectTests();,这个方法名就是mapper文件中的id值selectTests
         *
         * 3.通过返回值也可以确定Mybatis要调用的SqlSession的方法
         *   如果返回值是List,则调用selectList()方法
         *   如果返回值是int,则根据mapper文件中的标签确定是调用insert或是update方法
         * 4,mybatis中的动态代理
         *    mybatis根据dao的方法调用,获取执行sql语句的信息
         *    mybatis根据具体的dao接口,创建出一个dao接口的实现类,并创建这个类的对象
         *    完成SqlSession调用方法,访问数据库
         * */
        TestDao test = new TestDaoImpl();
        List<customDAO.Test> tests = test.selectTests();
        tests.forEach(test1 -> System.out.println(test1));
    }
}

Use dynamic proxy

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class TestMybatis
{
    
    
    @Test
    public void testSelectTests()
    {
    
    
        /**
         * 使用mybatis的动态代理机制,使用SqlSession.getMapper(dao接口)方法
         * 这个方法能获取dao接口对应的实现类对象
         **/
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        TestDao testDao = sqlSession.getMapper(TestDao.class);
        //调用dao的方法,执行数据库的操作
        List<customDAO.Test> tests = testDao.selectTests();
        tests.forEach(test1 -> System.out.println(test1));
    }
}

Four, Mybatis tools

SqlSession can be obtained directly through the tool class, avoiding a lot of duplication of code

package HelloMybatis;

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 java.io.InputStream;
//工具类,获取SqlSession
public class MybatisUtil
{
    
    
    private static SqlSessionFactory factory = null;
    static
    {
    
    
        String config = "mybatis.xml";
        try
        {
    
    
            InputStream in = Resources.getResourceAsStream(config);
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            factory = builder.build(in);
        }
        catch (Exception e)
        {
    
    
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession()
    {
    
    
        SqlSession sqlSession = null;
        if(factory != null)
        {
    
    
            sqlSession = factory.openSession();
        }
        return sqlSession;
    }
}

Guess you like

Origin blog.csdn.net/weixin_46841376/article/details/114490742