How to build Mybatis framework on your own Maven project?

Compilation software: IntelliJ IDEA 2019.2.4 x64
Operating system: win10 x64-bit Home Edition
Maven version: apache-maven-3.6.3
Mybatis version: 3.5.6



foreword

"Mybatis framework", "Mybatis framework"..., dismantling its nouns, we can get the simple conclusion that "Mybatis is the name of a framework", but what is a framework? What is Mybatis? And read this article to break it down for you.


1. What is the Mybatis framework?

1.1 What is a framework?

To give an example in life, when we work hard and save money to buy a house, can we buy a house that can be rented directly? When we spend money to buy our own personal computers, can we use them as soon as we buy them? No, the house we bought is just a rough-and-ready room, which requires later decoration and additional furniture before we can move in; the computer we bought requires us to set the corresponding system parameters when we turn it on for the first time, such as setting up the network and login account or creating an account, etc. , to be used.

The framework is equivalent to the blank room and the newly bought but unconfigured computer in the above example . The 半成品same is true for the framework in the Java program, and the same is true for the framework in other languages.

Common frameworks in Java programs [back-end development] are:

  1. Mybatis框架: Persistence layer framework [dao layer]
  2. SpringMVC框架: Control layer framework [Servlet) layer]
  3. Spring框架: All-rounder

1.2 What is MyBatis?

  1. MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping
  2. MyBatis avoids almost all DBC code and manually setting parameters and getting result sets
  3. MyBatis can use simple XML or annotations for configuration and original mapping, and map interfaces and Java POJOs (Plain Ordinary Java Objects, ordinary Java objects) into records in the database
  4. Mybatis is a semi-automatic persistence layer ORM (Object Relation Mapping) framework

What are ORMs?

ORM (Object Relation Mapping) --> 【Object Relational Mapping】

Establish a mapping relationship between objects in java and tables in the database

The advantage is that manipulating objects in java can affect the data in tables in the database

Why is MyBatis called semi-automatic?

This is compared to real ORM frameworks (such as Hibernate, Spring Data JPA, etc.), Mybatis has a lower degree of automation in object-relational mapping.

In Mybatis, developers need to manually define the mapping rules between SQL statements and Java objects in XML files or annotations. This means that Mybatis does not automatically generate SQL statements and does not automatically convert between Java objects and database tables.

However, at the same time, Mybatis also provides many powerful SQL statement generation features, such as: dynamically splicing SQL statements, supporting the use of DAO layer interface agents to execute SQL statements, etc., enabling developers to operate databases more flexibly.

1.3 Where can I find the reference materials of MyBatis?

Source code address of MyBatis

The official document address of MyBatis


2. How to build the Mybatisi framework (entry case)?

No matter what framework is imported, it must go through the following three steps:

  1. import jar package
  2. Write a configuration file
  3. Use the core class library

Case requirements: Create a data table tbl_employee in the database, and create an Employee class in the maven project to find the corresponding employee information from the database according to the id (employee number), and try to use the mybatis framework to implement it

2.1 Prepare data

① Build a database, build a table, create constraints and import test data

CREATE TABLE tbl_employee(
id INT(11)PRIMARY KEY AUTO_INCREMENT,
last_name VARCHAR(50),
email VARCHAR(50),
salary DOUBLE(10,2)
);

insert image description here

② Prepare maven project

insert image description here

2.2 Steps to build Mybatis framework

2.2.1 Import the jar package in pop.xml under the maven project

We need the following three jar packages:

  • MySQL driver jar package 8.0.26
  • junit 4.12
  • The jar package of Mybatis framework 3.5.6

The sample code is as follows:

//pop.xml中导入相关jar包
<dependencies>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.26</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>



</dependencies>

2.2.2 Write the core configuration file [mybatis-config.xml]

Location:

under the resources directory

File naming:

It is recommended to use mybatis-config.xml

The code example is as follows:

The relevant code can be directly copied from https://mybatis.org/mybatis-3/zh/getting-started.html and pasted into your own core configuration file, as shown below.

insert image description here

insert image description here

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--   下面是mysql8版本            -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <!--    url后要加时区 ?serverTimezone=UTC" ,不然报错           -->
                <property name="url" value="jdbc:mysql://localhost:3306/0411db?serverTimezone=UTC"/>
            <!-- 下面是mysql5版本的写法
                 <property name="driver"value="com.mysql.jdbc.Driver"/>
                 <property name="url"value="jdbc:mysql://localhost:3306/0411db"/>
                -->
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    //设置映射文件的路径
    <mappers>
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    </mappers>
</configuration>

insert image description here

Notice:

If your MySQL version is 8 or above, add the time zone "?serverTimezone=UTC" after the url, otherwise an error will be reported

For different database versions of MySQL, the values ​​of diver and url will be written differently

Take my mysql database version (8.0.26) as an example as follows:

MySQL8 version:

<property naurlme="driver" value="com.mysql.cj.jdbc.Driver"/>
/url后要加时区“ ?serverTimezone=UTC" ,不然会报错
<property name="url" value="jdbc:mysql://localhost:3306/0411db?serverTimezone=UTC"/>

MySQL5 version:

<property name="driver"value="com.mysql.jdbc.Driver"/>
<property name="url"value="jdbc:mysql://localhost:3306/0411db"/>

2.2.3 Write related interfaces and mapping files

Mapping file location:

resources/mapper (this is a new package Mapper to store multiple mapping files)

Mapping file naming:

XXMapper.xml (recommended to be consistent with the naming of the corresponding Mapper interface)

The role of the mapping file:

Write sql statements for the corresponding Mapper interface

ps:

A xxxMapper interface corresponds to a mapping file XXMapper.xml

If there are multiple Mapper interfaces, there must be multiple corresponding mapping files in the resources directory, but the core configuration file is also stored in the resources directory. To distinguish the core configuration file from multiple mapping files, it is recommended to create a new package in the resources directory Mapper, used to store multiple mapping files

Notice:

  • 映射文件名与接口名保持一致
  • 映射文件namespace与接口全类名保持一致
  • 映射文件Select的Id的属性值与接口的方法名保持一致

insert image description here

Note:

insert image description here

The sample code is as follows:

① Define the EmployeeMapper interface under src\main\java\mybatis\mapper

package mybatis.mapper;

import mybatis.pojo.Employee;

public interface EmployeeMapper {
    
    
	//根据员工编号查找对应的员工信息
    public Employee selectByempId(int empId);

}

② Define the mapping file EmployeeMapper.xml corresponding to the EmployeeMapper interface under src\main\resources\mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="mybatis.mapper.EmployeeMapper">
    <!--  resultType:Mapper接口中selectByempId方法的返回值类型【Employee类(写类的全名称)】  -->
    <select id=" selectByempId" resultType="mybatis.pojo.Employee">
        select
            id,
            last_name,
            email,salary
        from
            tbl_employee
        where
            id= #{empId}
    </select>
</mapper>

Note: The relevant codes of the basic configuration information in the mapping file can be directly copied from https://mybatis.org/mybatis-3/zh/getting-started.html, pasted into your own mapping file, and modifying some parameter values. Can

insert image description here

2.2.4 Test (using SqlSession object)

step:

①Get the SqlSessionFactory object first

②Get the SqlSession object again

③ Obtain the KXXMapper proxy object through the SqlSession object

④ test

The code example is as follows:

import mybatis.mapper.EmployeeMapper;
import mybatis.pojo.Employee;
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 TestMybatis {
    
    

    @Test
    public void test01(){
    
    

        try {
    
    
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            //通过SqlSessionFactory对象调用openSession();
            SqlSession sqlSession = sqlSessionFactory.openSession();

            //获取EmployeeMapper的代理对象
            EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
            System.out.println(" employeeMapper.getClass().getName() = "+employeeMapper.getClass().getName());

            Employee employee = employeeMapper.selectByempId(1);
            System.out.println(employee);


        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

    }

}

insert image description here

2.3 Build log4j log framework

Why build a log4j logging framework?

The log4j logging framework can display the underlying running process of mybatis, which is convenient for our developers to find bugs

step:

① Introduce the log4j jar package in the pop.xml of the module to be applied

The code example is as follows:

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

② Write its configuration file log4j.xml in the resources directory

The sample code is as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n" />
        </layout>
    </appender>
    <logger name="java.sql">
        <level value="debug" />
    </logger>
    <logger name="org.apache.ibatis">
        <level value="info" />
    </logger>
    <root>
        <level value="debug" />
        <appender-ref ref="STDOUT" />
    </root>
</log4j:configuration>

③ Run the test

insert image description here

Guess you like

Origin blog.csdn.net/siaok/article/details/130448994