Getting started with MyBatis framework

catalogue

1. Framework overview

1.1 three tier architecture

1.2 framework

2. Overview of mybatis framework

2.1 JDBC defects

2.2 overview of mybatis framework

3. Introduction case of mybatis

4. Introduction to main classes in mybatis

4.1 Resources class

4.2 SqlSessionFactoryBuilder class

4.3 SqlSessionFactory interface

4.4 SqlSession interface

5. Modification of introductory cases

5.1 usage of traditional dao

5.2 dynamic agent using Mybatis

1. Framework overview

1.1 three tier architecture

    The three-tier architecture includes interface layer, business logic layer and data access layer.

        ① Interface layer (presentation layer, view layer): the main function is to receive user data and display the processing results of requests. (jsp,

          html,servlet)

        ② Business logic layer: receive the data transferred from the presentation, check the data, calculate the business logic, and call the data access layer to obtain

          data

        ③ Data access layer (persistence layer): dealing with the database. It mainly realizes the addition, deletion, modification and query of data, and stores it in the data

          The data in the library is submitted to the business layer, and the data processed by the business layer is saved to the database.

    Package corresponding to layer 3:

        ① Interface layer: controller package (XXXServlet class)

        ② Business logic layer: service package (XXXService class)

        ③ Data access layer: dao package (XXXDao class)

    Class interaction in layer 3:

        User interface layer -- > business logic layer -- > data access layer -- > Database

    Processing framework corresponding to three layers:

        Interface layer -- servlet class -- spring MVC framework

        Business logic layer -- service class -- spring Framework

        Data access layer -- dao class -- mybatis framework

1.2 framework

    Framework is the reusable design of the whole or part of the system, which is expressed as a method of interaction between a group of abstract components and component instances. It can also be regarded as an application framework and template that can be customized by application developers. In short, framework is actually semi-finished software, that is, a group of components for you to use to complete your own system. Framework is safe, reusable and continuous Upgraded software.

    Some basic functions are defined in the framework. You can add your own functions to the project, and the functions you add can also use the functions written in the framework.

    Frame features:

        ① The framework is generally not omnipotent and can't do everything;

        ② The framework is effective for a certain field. For example, mybatis is strong in database operation, but not good at it

          His;

        ③ Framework is a software.

2. Overview of mybatis framework

2.1 JDBC defects

    ① There are many codes and the development efficiency is low;

    ② You need to pay attention to the creation and destruction of Connection, Statement and ResultSet objects;

    ③ The results of the ResultSet query need to be encapsulated as a List;

    ④ There are many duplicate codes;

    ⑤ Business code is mixed with database operation.

2.2 overview of mybatis framework

    mybatis framework, early called ibatis, its source code is on github.

    Mybatis is the MyBatis SQL Mapper Framework for Java(sql mapping framework), including:

        ① sql maper: sql mapping. You can map a row of data in the database table to a java object, that is, a row of data can be mapped

          As a java object, operating this object is equivalent to operating the data in the table.

        ② Data Access Objects(Daos): data access, adding, deleting, modifying and querying the database.

    Functions provided by mybatis:

        ① It provides the ability to create Connection, Statement and ResultSet without requiring developers to create these objects.

        ② It provides the ability to execute sql statements without developers.

        ③ It provides the ability to cycle sql and convert the results of sql into java objects and List sets.

                In JDBC, you can only:

                        while (rs.next()) {
                                Student stu = new Student();
                                stu.setId(rs.getInt("id"));
                                stu.setName(rs.getString("name"));
                                stu.setAge(rs.getInt("age"));
                                // Take out the data from the database, turn it into a Student object, and encapsulate it into a List collection
                                stuList.add(stu);
                         }

        ④ It provides the ability to close resources without manually closing Connection, Statement and ResultSet.

    Process: the developer provides sql statements -- mybatis processes and executes sql statements -- the developer obtains List sets or Java objects (data in tables)

    Summary: mybatis is an sql mapping framework. It refers to the ability to operate the database, which is equivalent to enhanced JDBC. Using mybatis allows developers to concentrate on writing sql statements without worrying about the creation and destruction of Connection, Statement, ResultSet and the execution of sql statements.

3. Introduction case of mybatis

    1. Create mysql database and table. The database name is springdb and the table name is student.

    2. Create a maven project, and select Maven archetype QuickStart as the skeleton. Add the dependency driven by mybatis and mysql to the pom.xml file.

<!--mybatis rely on-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.1</version>
</dependency>
<!--sql Drive dependency-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.9</version>
</dependency>

    3. Create entity class and Student class to save a row of data in the table. The package of entity class is called domain or entity.

package com.bjpowernode.domain;
//Recommendations are as easy to remember as table names
public class Student {
    //Define attributes. At present, the attribute name and column name are required to be the same.
    private Integer id;
    private String name;
    private String email;
    private Integer age;

    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 getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

    4. Create the dao interface of the data access layer and define the method of operating the database. The package name is dao.

package com.bjpowernode.dao;

import com.bjpowernode.domain.Student;
import java.util.List;
//Interface operation Student table
public interface StudentDao {

    //Query all data of Student table
    public List<Student> selectStudents();

    //Insertion method
    //Parameter: student, indicating the data to be inserted into the database
    //Return value: int indicates the number of rows affecting the database after the insert operation (several rows of data have been successfully added)
    public int insertStudent(Student student);
}

    5. Create a configuration file used by mybatis, called sql mapping file, to write sql statements. Generally, a table contains an sql mapping file, which is an XML file. The file is written in the directory where the dao interface is located (dao folder), and the file name is consistent with the dao interface name. StudentDao.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.bjpowernode.dao.StudentDao">
    <select id="selectStudents" resultType="com.bjpowernode.domain.Student">
       select id,name,email,age from student order by id
    </select>

    <!--
        select: Represents a query operation.
        id: What do you want to do sql The unique identifier of the syntax, mybatis Will use this id To find the to execute sql sentence
            It can be customized, but you are required to use the method name in the interface.

        resultType: Indicates the result type, yes sql Obtained after statement execution ResultSet,Traverse this ResultSet obtain java The type of the object.
                    The fully qualified name of the type to which the value is written

    -->
    <select id="insertStudent">
        insert into student values (#{id},#{name},#{email},#{age})
    </select>
</mapper>
<!--
     sql Mapping file(sql mapper): write sql Statement, mybatis Will perform these sql
     1.Specify constraint file
          <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

       mybatis-3-mapper.dtd Is the name of the constraint file and the extension is dtd of

     2.Function of constraint file: limit. Check that the labels and attributes appearing in the current file must meet the requirements mybatis Requirements

     3.mapper: Is the root label of the current file. It is required.
       namespace: It is called a namespace. The unique value can be a custom string.
                  Required use dao Fully qualified name of the interface

     4.Specific labels can be used in the current file to represent specific operations of the database.
        <select>: Means to execute a query, select sentence
        <update>: Indicates the operation of updating the database<update>The label says update sentence
        <insert>: Means insert, put insert sentence
        <delete>: Indicates deletion, which is executed by delete sentence
-->

    6. Create the main configuration file of mybatis: one project has one main configuration file. The main configuration file provides the connection information of the database and the location information of the sql mapping file. Write in the resources folder. 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>
    <!--settings: control mybatis Global behavior-->
    <settings>
        <!--set up mybatis Output log-->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
    <!--
         Environment configuration: database connection information
         default: Must be with a environment of id Same value.
                  tell mybatis The connection information of which database to use, that is, which database to access.
    -->
    <environments default="mydev">
        <!--
            environment: A database information configuration, environment
            id: A unique value, custom, that represents the name of the environment.
        -->
        <environment id="mydev">
            <!--
                 transactionManager: mybatis Transaction type
                 type: JDBC(Indicates use jdbc Medium Connection Object commit,rollback (transaction processing)
            -->
            <transactionManager type="JDBC"/>
            <!--
                 dataSource: Represents a data source, which is connected to a database
                 type: Represents the type of data source, POOLED Indicates that connection pool is used
            -->
            <dataSource type="POOLED">
                <!--
                    driver,url,username,password It is fixed and cannot be customized.
                -->
                <!--Database driver class name-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--Connecting to the database url character string-->
                <property name="url" value="jdbc:mysql://localhost:3306/springdb"/>
                <!--User name to access the database-->
                <property name="username" value="root"/>
                <!--password-->
                <property name="password" value="123456"/>
            </dataSource>
        </environment>

        <!--Represents the online library, which is the library actually used by the project-->
        <environment id="online">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/onlinedb"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--sql mapper(sql Location of the mapping file)-->
    <mappers>
        <!--
            One mapper Label specifies the location of a file.
            Path information starting from the classpath. target/classes((classpath)
        -->
        <mapper resource="com/bjpowernode/dao/StudentDao.xml"/>
        <!--<mapper resource="com/bjpowernode/dao/SchoolDao.xml"/>-->
    </mappers>
</configuration>

<!--
     mybatis Main configuration file: mainly defines the configuration information of the database, sql Location of the mapping file

     1.Constraint file
        <!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

       mybatis-3-config.dtd: Name of the constraint file

     2.configuration Root label
-->

    7. Create and use the mybatis class to access the database through mybatis.

package com.bjpowernode;

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

public class MyApp {
    public static void main(String[] args) throws IOException {
        //Access mybatis and read student data
        //1. Define the name of the mybatis main configuration file, starting from the end of the classpath (target/classess)
        String config = "mybatis.xml";
        //2. Read the file represented by this config
        InputStream in  = Resources.getResourceAsStream(config);
        //3. Created SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //4. Create SqlSessionFactory object
        SqlSessionFactory factory = builder.build(in);
        //5. [important] get the SqlSession object and get the SqlSession from the SqlSessionFactory
        SqlSession sqlSession = factory.openSession();
        //6. [important] specifies the identification of the sql statement to be executed. id value of namespace + ".. + tag in sql mapping file
        String sqiId = "com.bjpowernode.dao.StudentDao" + "." + "selectStudents";
        //7. Execute sql statement and find the statement through sqlId
        List<Student> studentList = sqlSession.selectList(sqiId);
        //8. Output results
        //studentList.forEach( stu -> System.out.println(stu));
        for (Student stu:studentList){
            System.out.println(stu);
        }
        //9. Close the SqlSession object
        sqlSession.close();
    }
}
public class TestMybatis {
    //Test method, test function
    @Test
    public void testInsert() throws IOException {
        //Access mybatis and read student data
        //1. Define the name of the mybatis main configuration file, starting from the end of the classpath (target/classess)
        String config = "mybatis.xml";
        //2. Read the file represented by this config
        InputStream in  = Resources.getResourceAsStream(config);
        //3. Created SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //4. Create SqlSessionFactory object
        SqlSessionFactory factory = builder.build(in);
        //5. [important] get the SqlSession object and get the SqlSession from the SqlSessionFactory
        //SqlSession sqlSession = factory.openSession();
        SqlSession sqlSession = factory.openSession(true);//Auto commit transaction
        //6. [important] specifies the identification of the sql statement to be executed. id value of namespace + ".. + tag in sql mapping file
        String sqiId = "com.bjpowernode.dao.StudentDao" + "." + "insertStudent";
        //7. Execute sql statement and find the statement through sqlId
        Student student = new Student();
        student.setId(1005);
        student.setName("Guan Yu");
        student.setEmail("guanyu@163.com");
        student.setAge(20);
        int num = sqlSession.insert(sqiId,student);
        //mybatis does not commit transactions automatically by default, so transactions should be submitted manually after insert, update and delete
        //sqlSession.commit();
        //8. Output results
        System.out.println("implement insert result:" + num);
        //9. Close the SqlSession object
        sqlSession.close();
    }
}

    8. Create a tool class to implement the repeated code in the first half.

package com.bjpowernode.utils;

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;

public class MyBatisUtils {

    private static SqlSessionFactory factory = null;

    static {
        String config = "mybatis.xml";
        try {
            InputStream in = Resources.getResourceAsStream(config);
            //Create a SqlSessionFactory object and use SqlSessionFactoryBuilder
            factory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //Method to get SqlSession
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = null;
        if(factory != null){
            sqlSession = factory.openSession();//Non auto commit transaction
        }
        return sqlSession;
    }
}

    9. Use the tool class to realize the query function.

public class MyApp2 {
    public static void main(String[] args) throws IOException {
        //[important] get the SqlSession object and get the SqlSession from the SqlSessionFactory
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        //[important] specify the identification of the sql statement to be executed. id value of namespace + ".. + tag in sql mapping file
        String sqiId = "com.bjpowernode.dao.StudentDao" + "." + "selectStudents";
        //Execute the sql statement and find the statement through sqlId
        List<Student> studentList = sqlSession.selectList(sqiId);
        //Output results
        //studentList.forEach( stu -> System.out.println(stu));
        for (Student stu:studentList){
            System.out.println(stu);
        }
        //9. Close the SqlSession object
        sqlSession.close();
    }
}

    In this example, the dao interface is not used. This interface is not necessary, but in our later development, we use the methods in this interface to access the database and add, delete, modify and query.  

4. Introduction to main classes in mybatis

4.1 Resources class

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

        InputStream in = Resources.getResourceAsStream("mybatis.xml");

4.2 SqlSessionFactoryBuilder class

    Responsible for creating SqlSessionFactory objects.

        SqlSessionFactoryBuilder builder  = new SqlSessionFactoryBuilder();

        // Create SqlSessionFactory object

        SqlSessionFactory factory = builder.build(in);

4.3 SqlSessionFactory interface

    For heavyweight objects, the program creates one, which takes a long time and uses more resources. In the whole project, one object is enough, so it can be created by using the static code block in the tool class.

    SqlSessionFactory: interface. Interface implementation class: DefaultSqlSessionFactory.

    SqlSessionFactory function: get SqlSession object.

        SqlSession sqlSession = factory.openSession();

    Description of openSession() method:

         1. openSession(): if there are no parameters, obtain the SqlSession object that is a non auto commit transaction

        2. openSession(boolean):

                 openSession(true)   Gets the SqlSession. Of the auto commit transaction  

                 openSession(false)   SqlSession object for non auto commit transactions

4.4 SqlSession interface

    Defines methods for manipulating data, such as selectOne()     selectList()     insert()     update()     delete()     commit()     rollback().

    The implementation class of SqlSession interface is DefaultSqlSession.

    Usage requirements: the SqlSession object is not thread safe and needs to be used inside the method. Before executing the sql statement, use openSession() to obtain the SqlSession object. After executing the sql statement, you need to close it and execute SqlSession.close(). This ensures that his use is thread safe.

5. Modification of introductory cases

5.1 usage of traditional dao

    1.dao interface:

package com.bjpowernode.dao;

import com.bjpowernode.domain.Student;

import java.util.List;

public interface StudentDao {
    List<Student> selectStudents();
    int insertStudent(Student student);
}

    2. Implementation class of Dao interface:

package com.bjpowernode.dao.impl;

import com.bjpowernode.dao.StudentDao;
import com.bjpowernode.domain.Student;
import com.bjpowernode.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class StudentDaoImpl implements StudentDao {
    @Override
    public List<Student> selectStudents() {
        //Get SqlSession object
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        String sqlid = "com.bjpowernode.dao.StudentDao.selectStudents";
        //Execute the sql statement and use the method of SqlSession class
        List<Student> students = sqlSession.selectList(sqlid);
        sqlSession.close();
        return students;
    }

    @Override
    public int insertStudent(Student student) {
        //Get SqlSession object
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        String sqlid = "com.bjpowernode.dao.StudentDao.insertStudent";
        //Execute the sql statement and use the method of SqlSession class
        int nums = sqlSession.insert(sqlid,student);
        //Commit transaction
        sqlSession.commit();
        sqlSession.close();
        return nums;
    }
}

    3. Test method:

public class TestMyBatis {
    @Test
    public void testSelectStudents(){
        //com.bjpowernode.dao.StudentDao
        StudentDao dao = new StudentDaoImpl();
        /*
             List<Student> students = dao.selectStudents(); call
             1.dao Object, the type is StudentDao, and the fully qualified name is com.bjpowernode.dao.StudentDao
               A fully qualified name is the same as a namespace.

             2.The method name, selectStudents, is the id value in the mapper file
               
               1 After the string obtained from and 2 is spliced, it is the sqlid we need to use before

             3.The method of SqlSession to be called by MyBatis can also be determined by the return value type of the method in dao
                  If the return value type is List, the SqlSession.selectList() select method is called
                  If the return value type is int or non List, if the label in the mapper file is < Insert >, < update > will call
                  SqlSession insert, update, etc
             
             In this way, it is found that the above information can be obtained through a method call, so the reflection mechanism can be used.

             mybatis Dynamic proxy: mybatis obtains the information of executing sql statements according to dao's method calls.
                               mybatis According to your dao interface, create an implementation class of dao interface and create the object of this class.
                               Complete the SqlSession call method to access the database.
                               So you don't need to write your own dao implementation class. mybatis is implemented automatically using dynamic proxies.
         */
        List<Student> students = dao.selectStudents();
        for(Student student : students){
            System.out.println(student);
        }
    }

    @Test
    public void testInsertStudent(){
        StudentDao dao = new StudentDaoImpl();
        Student student = new Student();
        student.setId(1006);
        student.setName("Shield mountain");
        student.setEmail("dunshan@163.com");
        student.setAge(22);
        int nums = dao.insertStudent(student);
        System.out.println("Number of objects added:" + nums);
    }
}

5.2 dynamic agent using Mybatis

    1.dao interface:

public interface StudentDao {
    List<Student> selectStudents();
    int insertStudent(Student student);
}

    2. Test method using dynamic agent:

        The object of SqlSession has a method getMapper().

public class TestMyBatis {
    @Test
    public void testSelectStudents(){
        /**
         * Use the dynamic proxy mechanism of mybatis and SqlSession.getMapper(dao interface)
         * getMapper It can obtain the implementation class object corresponding to dao interface.
         */
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);//Using reflection mechanism
        //Dao = com. Sun. Proxy. $proxy2: dynamic proxy for JDK
        System.out.println("dao=" + dao.getClass().getName());
        //Call dao's method to perform database operations
        List<Student> students = dao.selectStudents();
        for (Student student : students){
            System.out.println(student);
        }
        sqlSession.close();
    }

    @Test
    public void testInsertStudent(){
        Student student = new Student();
        student.setId(1007);
        student.setName("Li Fei");
        student.setEmail("lifei@163.com");
        student.setAge(22);
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        int nums = dao.insertStudent(student);
        sqlSession.commit();
        System.out.println("Number of objects added:" + nums);
        sqlSession.close();
    }
}

PS: sort out according to the power node course. If there is infringement, contact to delete it.

Keywords: Mybatis Java framework

Added by rockyracoon on Tue, 26 Oct 2021 10:51:26 +0300