Mybatis Framework -- Basic Introduction

Posted by maineyak on Sat, 03 Aug 2019 10:14:39 +0200

Introduction to Mybatis

Mybatis is a persistence framework, ORM framework, is the top-level project under Apache, supporting customized SQL, stored procedures and advanced mapping.
Mybatis avoids all JDBC code and manual parameter setting and result set acquisition in the JDBC programming process. Mainly let the developer mechanism focus on SQL and get data through mapping provided by mybatis

Object Relational Mapping (ORM, or O/RM, or O/R mapping) is used to transform data between different types of systems in object-oriented programming languages. Simply put, ORM maps objects in programs to relational databases by using metadata that describes the mapping between objects and databases.

JDBC Problems

1. The connection of database is created when it is used, closed when it is not used, frequent opening and closing of database will affect the performance of database.
Solution: Solution through connection pool
2. Hard-coded SQL statements into JAVA code. If the SQL is modified, the JAVA code needs to be modified for compilation and execution, which is not conducive to system maintenance.
Solution: Configuring SQL statements in xml files eliminates the need to modify java code
3. Traversing the result set data from the resultSet is that there is hard coding and the fields of the acquired data table are hard-coded.
Solution: Mapping the result set of a query to a JAVA object

Mybatis Common Programming Steps

1. Create an employee table under mybatis database:

At this point, there is only one data in this table, and we will query this data.

2. To create a maven project, first introduce dependencies:

 <!--mysql Connection database driver-->
 <dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <version>5.1.39</version>
 </dependency>
 <!--mybatis Dependence-->
 <dependency>
     <groupId>org.mybatis</groupId>
     <artifactId>mybatis</artifactId>
     <version>3.4.1</version>
 </dependency>
     <!--log4j Log dependency-->
     <dependency>
       <groupId>log4j</groupId>
       <artifactId>log4j</artifactId>
       <version>1.2.17</version>
     </dependency>

3. Configure the global configuration file mybatis-config.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>
    <!--Configuration file for loading connection parameters of database-->
    <!--<properties resource="jdbc.properties"/>-->
    
    <!--Configure the running environment  (stay Spring Not in use)-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            </dataSource>
        </environment>
    </environments>
    
</configuration>

4. Write the corresponding bean layer Employee class:
Correspond to the information in the database

public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private String gender;

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", gender='" + gender + '\'' +
                '}';
    }

    public String getEmail() {
        return email;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getId() {
        return id;
    }

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

5. Write the corresponding XML Mapping file EmployeeMapper.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 Namespace special effects: if used mapper Dynamic proxy methods, which need to be configured here mapper Interface Address-->
<mapper namespace="Bean.Employee">
    <!-- id Consistent with the calling method, parameterType For parameter type, resultType For return type-->
    <select id="getEmpById" resultType="Bean.Employee" databaseId="mysql">
        select * from tbl_employee where id = #{id}
    </select>
</mapper>

6. Register the mapping file EmployeeMapper.xml in the global configuration file mybatis-config.xml

<! - Make sure that the written sql mapping file (EmployeeMapper.xml) is registered with the global configuration file
    <mappers>
        <mapper resource="EmployeeMapper.xml"/>
    </mappers>

7. Test class:

Annotation of Programming Steps in Code

public class App1 {
    public static void main( String[] args ) throws IOException {
        //1. Create an SqlSessionFactory object from an xml configuration file (global configuration file)
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 2. Get the sqlSession instance and execute the mapped sql statement directly
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            Employee employee = sqlSession.selectOne("Bean.Employee.getEmpById", 1);
            System.out.println(employee);
        }finally {
            sqlSession.close();
        }
    }
}

Operation results:

Interface Programming

Next, let's demonstrate the interface programming steps of mybatis, which we will often use in the future. It encapsulates the method in the dao layer interface. In the access operation, a proxy object is obtained by reflection, and then the proxy object is used to invoke the method to realize the operation.

The steps for introducing dependencies, global configuration files, and creating databases are the same as the usual way above.

1. Write the corresponding bean class:
Correspond with database

public class Student {
    public int id;
    public String name;

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

    public int getSID() {
        return id;
    }
    public void setSID(int id) {
        this.id = id;
    }
    public String getSName() {
        return name;
    }
    public void setSName(String name) {
        this.name = name;
    }
}

2. Write the interface Student Mapper of dao layer:
Here we need a way to query users through id

public interface StudentMapper {
    Student getUserById(Integer id);
}

3. Write the mapping file StudentMapper.xml:
Namespace namespace has a special function: if you use the mapper dynamic proxy method, you need to configure the mapper interface address here;
In the < Select > tag, id is the same as the calling method, parameterType is the parameter type and resultType is the return type.
In the middle is our sql statement.

<?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.StudentMapper">
    <resultMap id="BaseResultMap" type="Bean.Student" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="name" property="name" jdbcType="VARCHAR" />

    </resultMap>
    <!-- id Consistent with the calling method, parameterType For parameter type, resultType For return type-->
    <select id="getUserById" resultType="Bean.Student">
        select * from student where id = #{id}
    </select>
</mapper>

4. Register the mapping file StudentMapper.xml in the global configuration file mybatis-config.xml

<mappers>
        <mapper resource="EmployeeMapper.xml"/>
        <mapper resource="StudentMapper.xml"/>
    </mappers>

5. Surveying category:
Test steps:

  1. Getting mybatis configuration flow through Resource
  2. Obtain sqlSessionFaction object through SqlSessionFactoryBuilder
  3. Getting sqlSession objects through openSession() of sqlSessionFaction
  4. mapper Proxy Objects of dao Layer Obtained by Reflection
  5. Call the method of dao layer, output
@Test
    public void test1() throws IOException{
        try {
            /**
             * Getting mybatis configuration flow through Resource
             */
            InputStream resource = Resources.getResourceAsStream("mybatis-config.xml");
            /**
             * Get an instance of SqlSessionFactory
             */
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);
            /**
             * Get the SqlSession instance
             */
            SqlSession sqlSession = sqlSessionFactory.openSession();
            /**
             * Acquiring dao instances by reflection
             */
            StudentMapperAnnotation mapper = sqlSession.getMapper(StudentMapperAnnotation.class);

            Student student = mapper.getUserById(1);
            System.out.println(student.getClass());
            System.out.println(student);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Operation results:

Topics: Mybatis xml SQL Database