Brief introduction and implementation of MyBatis detailed explanation framework

MyBatis framework

Chapter I framework

1. Three tier architecture

mvc: in web development, mvc architecture pattern is used. m: Data, v: view, c: controller

c controller: accept the request, call the service object, and display the processing result of the request. The servlet is currently used as the controller

v: now use jsp, html, css,js. Display the processing result of the request and display the data in m.

m data: from database mysql, from file, from network.

mvc function:

1). Realize decoupling

2). Let mvc take their own responsibilities

3) make the system expand better. Easier to maintain.

Three tier architecture

1. Interface layer (view layer): accept the user's request, call service and display the processing results of the request. It contains jsp,html,servlet and other objects.

2. Business logic layer: process business logic and use algorithms to process data. Return the data to the interface layer. The corresponding is the service package, which is similar to many in the package

XXXService class. For example: StudentService, OderService,ShopService

3. Persistence layer (database access layer): access the database, read files, and access the network. Get data. The corresponding package is dao. There are many students dao, oder dao, shopdao and so on in dao package

2. Processing flow of three-tier architecture request

User initiated request - > interface layer - > business logic layer - > persistence layer - > Database (mysql)

3. Why use a three-tier architecture

1. Clear structure, low coupling and clear division of labor at each layer.

2. High maintainability and expansibility.

3. Conducive to standardization.

4. Developers can only focus on the function implementation of one layer in the whole structure.

5. It is conducive to the reuse of logic at each layer.

4. Three tier architecture mode and framework

Each layer corresponds to a frame

1. Interface layer - spring MVC framework

2. Business layer - Spring Framework

3. Persistence layer - MyBatis framework

5. Framework

1) What is a framework

A framework is a piece of software that completes some of its functions. Classes in software and method calls between classes have been specified. Some functions can be completed through these. The framework is seen as a template.

The framework can be upgraded and transformed. The framework is secure.

The framework is useful for one aspect, not omnipotent.

6. Issues addressed by the framework

1) The framework can realize the integration of technology.

2) Improve the efficiency of development. Reduce the difficulty.

7. Advantages and disadvantages of JDBC accessing database

advantage:

1. Intuitive and easy to understand.

Disadvantages:

1. Create many objects: connection, statement and resultset

2. Register driver

3. Execute sql statement

4. Convert ResultSet to Student List set.

5. Close resources

6.sql statements are mixed with business logic code.

8.MyBatis framework

What is mybatis: it is a persistence layer framework, formerly known as ibatis, which was renamed mybatis in 2013. Mybatis can operate the database and add, delete, modify and query the database. As an advanced jdbc. Solve the shortcomings of jdbc.

What can MyBatis do?

1) Register driver

2) Create connection, statement and resultset used in jdbc

3) Execute the sql statement to get the ResultSet

4) Handle the ResultSet, convert the data in the recordset into Java objects, and put Java objects into the List set.

5) Close the resource.

6) Realize the decoupling of sql statements and java code.

MyBatis official website: https://mybatis.org/mybatis-3/zh/index.html

Chapter 2 Introduction to MyBatis

In this part, query 2.1-2.4 is not implemented completely with the help of the framework

Finally, maximize the use of the framework to simplify operation 2.5

2.1 first example

Implementation steps:

1. Create student table (id,name,email,age)

2. New maven project

3. Modify pom.xml

1) add MyBatis dependency, mysql driver and junit

2) add resource plug-ins in < * Build >

4. Create the entity class Student, define the attribute, and keep the attribute name consistent with the column name.

5. Create Dao interface and define the method of operating database.

6. Create an xml file (mapper file) and write sql statements.

The mybatis framework recommends separating sql statements from java code.

Mapper file: the definition and dao interface are in the same directory, one table and one mapper file.

7. Create the main configuration file (xml file) of mybatis: there is one in the resources directory

1) define the data source object to create the connection instance

2) specify the location of other mapper files.

8. Create test content.

Using the main method, test mybatis to access the database

You can also use junit to access the database.

Ask only the hard work, not the harvest

Concrete implementation

3.Maven's pom.xml file

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <!-- Coordinates of the current project-->
  <groupId>com.bjpowernode</groupId>
  <artifactId>ch01-first</artifactId>
  <version>1.0</version>



  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <!--Dependency list-->
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!--mybatis rely on -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <!-- mysql drive-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>
  </dependencies>

  <build>
    <!--Resource plug-ins: Processing src/main/java In the directory xml-->
    <resources>
      <resource>
        <directory>src/main/java</directory><!--Directory where-->
        <includes><!--Including the.properties,.xml All files will be scanned-->
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>

    <!-- appoint jdk We have specified the version of, so we don't need it now-->
<!--    <plugins>-->
<!--      <plugin>-->
<!--        <artifactId>maven-compiler-plugin</artifactId>-->
<!--        <version>3.1</version>-->
<!--        <configuration>-->
<!--          <source>1.8</source>-->
<!--          <target>1.8</target>-->
<!--        </configuration>-->
<!--      </plugin>-->
<!--    </plugins>-->


  </build>
</project>

5. Create Dao interface and define the method of operating database.

The domain layer under Java writes the Student class, and the dao layer writes the StudentDao interface. Write StudentDao.xml in the same directory

package com.sunny.dao;

import com.sunny.domain.Student;

public interface StudentDao {

    //Query a student
    Student selectStudentById(Integer id);
}

6. Create an xml file (mapper file) and write sql statements.

<?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.sunny.dao.StudentDao">
<!--    <select id="selectBlog" resultType="Blog">
        select * from Blog where id = #{id}
    </select>-->
<!--    Query a student Student
        <select>:Represents a query operation, which is select sentence
        id:To execute sql The unique identifier of the statement is a custom string.
            Recommended use dao Method name in interface
        resultType:tell mybatis,implement sql Statement, which type of data is assigned to java Object.
            resultType The value of is now used java The fully qualified name of the object

		        #{studentId}: placeholder, representing the data passed in from the java program.
-->
    <select id="selectStudentById" resultType="com.bjpowernode.domain.Student">
        select id,name,email,age from student where id= #{studentId}
    </select>
<!--    add to insert
        insert into student values (1003,"Li Feng","lifeng@qq,com",26)
        If passed to mybatis It's a java Objects, using#{property name} gets the value of this property.
        Attribute value to#Location of {} placeholder, mybatis executes getXXX() corresponding to this property
        for example#{id}, execute getId()
-->
    <insert id="insertStudent">
        insert into student values (#{id},#{name },#{email},#{age})
    </insert>
</mapper>

<!--
    1.Constraint file
        http://mybatis.org/dtd/mybatis-3-mapper.dtd
        Role of constraint file: define and limit the labels and attributes that can be used in the current file, as well as the order in which labels appear
    2.mapper Is the root label
      namespace:  Namespace, must have a value, cannot be empty. Unique value.
                  Recommended use Dao The fully qualified name of the interface.
      Role: participate in identification sql Statement.
    3.stay mapper It can be written inside<insert>,<update>,<delete>,<select>And other labels.
    <insert> Inside insert Statement that represents the insert Operation.
    <update> Inside update sentence
    <delete> Inside delete sentence
    <select> Inside select sentence

-->

7. Create the main configuration file (xml file) of mybatis: there is one in the resources directory

?useUnicode=true&characterEncoding=utf-8

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
<!--         Configuring data sources: Creating Connection object-->
            <dataSource type="POOLED">
<!--             driver:Driven content-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
<!--                Connecting to the database url-->
                <property name="url" value="jdbc:mysql://localhost:3306/springdb?useUnicode=true&amp;
                characterEncoding=utf-8"/>
<!--                user name-->
                <property name="username" value="root"/>
<!--                password-->
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
<!--    Specify other mapper File location:
        other mapper The purpose of the file is to find other files sql sentence.
-->
    <mappers>
<!--        
        use mapper of resource Attribute assignment mapper The path to the file.
        This path is from target/classes The path is open.
        
        Usage Note:
            resource = mapper File path, using/Split path
            One mapper resource Specify a mapper file
-->
        <mapper resource="com/bjpowernode/dao/StudentDao.xml"/>
<!--        <mapper resource="com/bjpowernode/dao/OrderDao.xml"/>-->
<!--        <mapper resource="com/bjpowernode/dao/UserDao.xml"/>-->
    </mappers>
</configuration>

Test the code in the test file

package com.sunny;

import com.bjpowernode.domain.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;

public class MyTest {

    //Test mybatis to execute sql statements
    @Test
    public void testSelectStudentById() throws IOException {
//         Call the method of an object in mybatis and execute the sql statement in the mapper file.

//         mybatis core class: SqlSessionFactory

//        1. Define the location of the mybatis master configuration file and the relative path starting from the class path
        String config = "mybatis.xml";

//        2. Read the master configuration file. Use the Resources class in the mybatis framework
        InputStream inputStream = Resources.getResourceAsStream(config);

//        3. Create SqlSessionFactory object and use SqlSessionFactoryBuilder class
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//        4. Get SqlSession object
        SqlSession session = factory.openSession();
//        5. Specify the id of the sql statement to be executed
//        id of sql = namespace + ". + < Select > |update|insert|delete tag id attribute value.
        String sqlId="com.bjpowernode.dao.StudentDao"+"."+"selectStudentById";

//        6. Execute sql statements through the SqlSession method.
        Student student = session.selectOne(sqlId);
        System.out.println("use mybatis Query a student"+student);

//        7. Close the SqlSession object
        session.close();
    }
    
    @Test
    public void testSelectStudentById2() throws IOException {
//         Call the method of an object in mybatis and execute the sql statement in the mapper file.

//         mybatis core class: SqlSessionFactory

//        1. Define the location of the mybatis master configuration file and the relative path starting from the class path
        String config = "mybatis.xml";

//        2. Read the master configuration file. Use the Resources class in the mybatis framework
        InputStream inputStream = Resources.getResourceAsStream(config);

//        3. Create SqlSessionFactory object and use SqlSessionFactoryBuilder class
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//        4. Get SqlSession object
        SqlSession session = factory.openSession();
//        5. Specify the id of the sql statement to be executed
//        id of sql = namespace + ". + < Select > |update|insert|delete tag id attribute value.
        String sqlId="com.bjpowernode.dao.StudentDao"+"."+"selectStudentById";

//        6. Execute sql statements through the SqlSession method.
        Student student = session.selectOne(sqlId,1002);
        System.out.println("use mybatis Query a student"+student);

//        7. Close the SqlSession object
        session.close();
    }

    @Test
    public void testInsertStudent() throws IOException {

        String config = "mybatis.xml";
        InputStream inputStream = Resources.getResourceAsStream(config);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession session = factory.openSession();

        String sqlId="com.bjpowernode.dao.StudentDao"+"."+"insertStudent";

//        6. Execute sql statements through the SqlSession method.
        Student student = new Student();
        student.setId(1005);
        student.setName("Fei Zhang");
        student.setEmail("zhangfei@qq.com");
        student.setAge(26);

        int rows = session.insert(sqlId,student);
        System.out.println("use mybatis Add a student, rows="+rows);

//        By default, MySQL executes sql statements in the mode of manual transaction submission. Transactions need to be submitted after insert, update and delete.
        session.commit();
//        7. Close the SqlSession object
        session.close();
    }

    @Test
    public void testAutoCommitInsertStudent() throws IOException {

        String config = "mybatis.xml";
        InputStream inputStream = Resources.getResourceAsStream(config);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession session = factory.openSession(true);

        String sqlId="com.bjpowernode.dao.StudentDao"+"."+"insertStudent";

//        6. Execute sql statements through the SqlSession method.
        Student student = new Student();
        student.setId(1007);
        student.setName("Little Joe");
        student.setEmail("zhangfei@qq.com");
        student.setAge(26);

        int rows = session.insert(sqlId,student);
        System.out.println("use mybatis Add a student, rows="+rows);


//        7. Close the SqlSession object
        session.close();
    }    
}

use mybatis Query a student Student Entity information{id=1001, name='Li Si', email='sunny@qq.com', age=21}

Process finished with exit code 0

2.2 concept

1. Auto commit: after your sql statement is executed, commit the transaction. The database update operation is saved directly to the database.

Add in mybatis.xml file

<configuration>
<!--    Set log-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

The optional values are: SLF4J, LOG4J, LOG4J2 and JDK_LOGGING,COMMONS_LOGGING,STDOUT_LOGGING,NO_LOGGING

This is a printing process for the console

Opening JDBC Connection
Created connection 161960012.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@9a7504c]
//Turn off the auto submit function;
//Then execute the sql statement
==>  Preparing: select id,name,email,age from student where id= ? 
    //The placeholder becomes a question mark parameter value
    //Parameter value
==> Parameters: 1002(Integer)
    //column
<==    Columns: id, name, email, age
    //Row value corresponding to column
<==        Row: 1002, Zhang San, zhangs@qq.com, 22
    //A row of records will be found this time.
<==      Total: 1
    //My own code output
 use mybatis Query a student Student Entity information{id=1002, name='Zhang San', email='zhangs@qq.com', age=22}
	//Set auto commit to true again, close the connection, and put the connection into the connection pool.
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@9a7504c]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@9a7504c]
Returned connection 161960012 to pool.

Process finished with exit code 0

2. Manually commit transactions: execute methods, commit transactions or review transactions where you need to commit transactions.

Prone problems

idea is sometimes useless to copy xml into the target.

resolvent:

1.Build

​ 2.maven - clean - compile

3. Restart idea file - > invalidate cache / restart

4. Copy the documents manually.

2.3 some important objects of mybatis

1) Resources: an object in the mybatis framework, which is used to read the main configuration information.

InputStream inputStream = Resources.getResourceAsStream(config);

2)SqlSessionFactoryBuilder: responsible for creating SqlSessionFactory objects

SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);

3)SqlSessionFactory: important object

SqlSessionFactory is a heavyweight object: creating this object requires more resources and time. Just have one heavyweight object in the project.

SqlSessionFactory interface: serves as a factory for SqlSession, which is to create a SqlSession object.

DefaultSqlSessionFactory implementation class

public class DefaultSqlSessionFactory implements SqlSessionFactory{}

Methods in SqlSessionFactory interface

openSession(): obtain a default SqlSession object. By default, transactions need to be submitted manually.

openSession(boolean):boolean indicates whether to automatically commit transactions.

true: create a SqlSession that automatically commits transactions

false: equivalent to openSession without parameters.

4) SqlSession object

The SqlSession object is obtained through SqlSessionFactory. SqlSession itself is an interface.

DefaultSqlSession: implementation class

public class DefaultSqlSession implements SqlSession {}

SqlSession provides a large number of methods to execute sql statements:

selectOne:implement sql Statement to get at most one line of records. More than one line is wrong.
selectList:implement sql Statement to return multiple rows of data.
selectMap:implement sql Statement to get a Map result.
insert: implement insert sentence.
update: implement update sentence.
delete: implement delete sentence.
commit: Commit the transaction.
rollback: Rollback transaction.

Note: SqlSession object is not thread safe. Use the following steps:

① : inside the method, obtain the SqlSession object before executing the sql statement

② : call the SqlSession method to execute the sql statement.

③ : close the SqlSession object and execute SqlSession.close()

2.4 idea tools and template functions

1. Create a template

File - > Settings - > editor - > file and templates - > file - > add custom template

Interface configuration file template content mybatis-mapper.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="dao Fully qualified name of the interface">
    <!-- use insert,update,delete,select Label write sql sentence-->	

</mapper>

Master profile template

<?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>
    <!--    Set log-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!--         Configuring data sources: Creating Connection object-->
            <dataSource type="POOLED">
                <!--             driver:Driven content-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--                Connecting to the database url-->
                <property name="url" value="jdbc:mysql://localhost:3306/springdb?useUnicode=true&amp;
                characterEncoding=utf-8"/>
                <!--                user name-->
                <property name="username" value="root"/>
                <!--                password-->
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>

        <mapper resource="Own interface xml file"/>

    </mappers>
</configuration>

2. Tools

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


/*
* Tool class: create sqlSession object
* */
public class MyBatisUtil {
    private static SqlSessionFactory factory = null;
    /*
    * The static code block allows the current class to create SqlSessionFactory once when the virtual machine is loaded.
    * */
    static{
        String config ="mybatis.xml";
        try {
            InputStream inputStream = Resources.getResourceAsStream(config);
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//    Create a method to get the SqlSession object
    public static SqlSession getSqlSession(){
        SqlSession session = null;
        if(factory!=null){
            session = factory.openSession();//openSession(true);
        }
        return session;
    }
}

Test class

public class MyTest {
    @Test
    public void testSelectById(){
//        1. Get SqlSession
        SqlSession session= MyBatisUtil.getSqlSession();
//        2. Specify sqlId
        String sqlId = "com.bjpowernode.dao.StudentDao.selectById";
//        3. The method of executing SqlSession indicates the execution of Sql statements
        Student student = session.selectOne(sqlId,1001);
        System.out.println("Query results==="+student);
//        4. Close the SqlSession object
        session.close();
    }
    @Test
    public void testSelectStudents(){
//        1. Get SqlSession
        SqlSession session= MyBatisUtil.getSqlSession();
//        2. Specify sqlId
        String sqlId = "com.bjpowernode.dao.StudentDao.selectStudents";
//        3. The method of executing SqlSession indicates the execution of Sql statements
        List<Student> students = session.selectList(sqlId);
        for(Student stu:students){
            System.out.println("student====="+stu);
        }
//        4. Close the SqlSession object
        session.close();
    }

    @Test
    public void testInsetStudent(){
//        1. Get SqlSession
        SqlSession session= MyBatisUtil.getSqlSession();
//        2. Specify sqlId
        String sqlId = "com.bjpowernode.dao.StudentDao.insertStudent";
//        3. The method of executing SqlSession indicates the execution of Sql statements
        Student student = new Student();
        student.setId(1008);
        student.setName("Eastern Emperor");
        student.setEmail("donghuang@qq.com");
        student.setAge(30);

        int rows = session.insert(sqlId,student);
        session.commit();
        System.out.println("insert Number of rows===="+rows);
//        4. Close the SqlSession object
        session.close();
    }
}

3.dao execute sql

Implement the interface with a class

import com.bjpowernode.dao.StudentDao;
import com.bjpowernode.domain.Student;
import com.bjpowernode.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class StudentDaoImpl implements StudentDao {
//    ctrl+o

    public StudentDaoImpl() {
        super();
    }

    @Override
    public Student selectById(Integer id) {
        SqlSession session = MyBatisUtil.getSqlSession();
        String sqlId = "com.bjpowernode.dao.StudentDao.selectById";
        Student student = session.selectOne(sqlId,1001);
        session.close();
        return student;
    }

    @Override
    public List<Student> selectStudents() {
//        1. Get SqlSession
        SqlSession session= MyBatisUtil.getSqlSession();
//        2. Specify sqlId
        String sqlId = "com.bjpowernode.dao.StudentDao.selectStudents";
//        3. The method of executing SqlSession indicates the execution of Sql statements
        List<Student> students = session.selectList(sqlId);

//        4. Close the SqlSession object
        session.close();
        return students;
    }

    @Override
    public int insertStudent(Student student) {
//        1. Get SqlSession
        SqlSession session= MyBatisUtil.getSqlSession();
//        2. Specify sqlId
        String sqlId = "com.bjpowernode.dao.StudentDao.insertStudent";
//        3. The method of executing SqlSession indicates the execution of Sql statements
        int rows = session.insert(sqlId,student);
        session.commit();
        System.out.println("insert Number of rows===="+rows);
//        4. Close the SqlSession object
        session.close();
        return rows;
    }
}

test method


public class MyTest2 {
    /*
    *SqlSession session= MyBatisUtil.getSqlSession();
    String sqlId = "com.bjpowernode.dao.StudentDao.selectById";
    *
    *
    * Test method: call dao's method
    * Student student = dao.selectById(1001);
    * 1)dao: The fully qualified type name can be obtained by reflection
    *   dao It is of Student type, fully qualified com.bjpwernode.dao.studentdao
    * 2)selectById:dao The method name is the id of the label in the mapper file
    *   sqlId="com.bjpowernode.dao.StudentDao.selectById" is obtained through dao.selectById();
    *
    * 3)Determines which method of SqlSession to call
    *   1.According to the method return of dao interface, if the return is an object, such as Student, call SqlSession.selectOne();
    *       If the method of dao interface returns List, call selectList() of SqlSession;
    *
    *   2.According to the label in the mapper file, if the label is < Insert >, call the SqlSession.insert() method
    *
    * mybatis Framework, it is found that the method call using dao can determine the necessary information for executing sql statements, and mybatis simplifies the implementation of dao objects.
    * The mybatis framework creates an object of the implementation class of the interface in memory according to your Dao interface during program execution.
    * mybatis This technology is called agent technology (dynamic agent, dao's dynamic agent).
    *
    * dao Proxy technology: mybatis creates the implementation class Proxy(StudentDaoImpl) of the StudentDao interface, which is replaced by the StudentDaoImpl created by the framework
    * You can't write the implementation class of dao interface for the function of StudentDaoImpl class manually implemented by yourself.
    *
    * Proxy requirements for using dao
    *   1.mapper namespace in file: must be the fully qualified name of dao interface
    *   2.mapper The id of the tag in the file is the method name in the dao interface (exactly the same)
    * */

    @Test
    public void testSelectOne(){
//        Method to use dao
//        Interface type variable = implementation class of new interface ();
        StudentDao dao = new StudentDaoImpl();

        Student student = dao.selectById(1001);
        System.out.println("adopt dao Execute the method to get the object==="+student);

    }
    @Test
    public void testSelectStudents(){
        StudentDao dao=new StudentDaoImpl();
        List<Student> students = dao.selectStudents();
        students.forEach(stu-> System.out.println("stu="+stu));
    }

    @Test
    public void testInsert(){
        StudentDao dao = new StudentDaoImpl();
        Student student = new Student();
        student.setId(1009);
        student.setName("Zhou Yu");
        student.setEmail("zhouqiang@qq.com");
        student.setAge(28);
        dao.insertStudent(student);
    }
}

2.5 dao agent

1.mybatis provides agents:

mybatis creates the implementation class object of Dao interface to complete the execution of sql statements. mybatis creates an object to implement class functions instead of your Dao.

2. Requirements for using mybatis agent:

1) the namespace in the mapper file must be the fully qualified name of the dao interface.

2) the id of the tag in the mapper file is the dao interface method name.

3. Implementation of mybatis agent

Use the method getMapper(dao.class) of the SqlSession object

For example, there is now a StudentDao interface.

SqlSession session = MyBatisUtils.getSqlSession();
StudentDao dao = session.getMapper(StudentDao.class);
Student student = dao.selectById(1001);

//In the above code
StudentDao dao = session.getMapper(StudentDao.class);
//Equivalent to
StudentDao dao = new StudentDaoImpl();
public class MyTest {

    @Test
    public void testSelectById(){
//        1. Get SqlSession
        SqlSession session= MyBatisUtil.getSqlSession();
//        2. Get the agent of dao
        StudentDao dao = session.getMapper(StudentDao.class);
        Student student = dao.selectById(1005);
        System.out.println("student = "+ student);
//        3. Close the SqlSession object
        session.close();
    }

    @Test
    public void testSelectStudents(){
        SqlSession session = MyBatisUtil.getSqlSession();
        StudentDao dao = session.getMapper(StudentDao.class);
        System.out.println("dao==="+dao.getClass());
//        dao===class com.sun.proxy.$Proxy2 proxy type. Instead of the function of the implementation class.
        List<Student> students = dao.selectStudents();
        students.forEach(stu-> System.out.println("stu="+stu));
        session.close();
    }

}
public class MyTest {

    @Test
    public void testSelectById(){
//        1. Get SqlSession
        SqlSession session= MyBatisUtil.getSqlSession();
//        2. Get the agent of dao
        StudentDao dao = session.getMapper(StudentDao.class);
        Student student = dao.selectById(1005);
        System.out.println("student = "+ student);
//        3. Close the SqlSession object
        session.close();
    }

    @Test
    public void testSelectStudents(){
        SqlSession session = MyBatisUtil.getSqlSession();
        StudentDao dao = session.getMapper(StudentDao.class);
        System.out.println("dao==="+dao.getClass());
//        dao===class com.sun.proxy.$Proxy2 proxy type. Instead of the function of the implementation class.
        List<Student> students = dao.selectStudents();
        students.forEach(stu-> System.out.println("stu="+stu));
        session.close();
    }

}

Tags: Java Database Mybatis mvc

Posted on Fri, 19 Nov 2021 10:37:22 -0500 by jponte