mybatis series summary

1. Introduction

1.1 what is mybatis

● MyBatis is an excellent persistence layer framework
● it supports custom SQL, stored procedures and advanced mapping.
● MyBatis eliminates almost all JDBC code and the work of setting parameters and obtaining result sets. MyBatis can configure and map primitive types, interfaces and Java POJO s (Plain Old Java Objects) to records in the database through simple XML or annotations.
● MyBatis was originally an open source project iBatis of apache. In 2010, the project was migrated from apache software foundation to google code and renamed MyBatis.
● moved to Github in November 2013.

Official documents of Mybatis: http://www.mybatis.org/mybatis-3/zh/index.html

GitHub : https://github.com/mybatis/mybatis-3

1.1.1 persistence

Persistence is a mechanism to convert program data between persistent state and transient state.

● save data (such as objects in memory) to a storage device that can be permanently saved (such as disk). The main application of persistence is to store the objects in memory in the database, or in disk files, XML data files and so on.

● JDBC is a persistence mechanism. File IO is also a persistence mechanism.

● in life: refrigerate fresh meat and thaw it when eating. The same is true of canned fruit.

Why do you need persistence services? That is caused by the defect of memory itself

● data will be lost after the memory is powered off, but some objects cannot be lost anyway, such as bank accounts. Unfortunately, people can't guarantee that the memory will never be powered off.

● memory is too expensive. Compared with external memory such as hard disk and optical disc, the price of memory is 2 ~ 3 orders of magnitude higher, and the maintenance cost is also high. At least it needs to be powered all the time. Therefore, even if the object does not need to be saved permanently, it will not stay in memory all the time due to the capacity limitation of memory, and it needs to be persisted to cache it to external memory.

1.2 durable layer

1.2.1 what is a persistence layer?

● code block to complete persistence. --- > Dao layer [DAO (Data Access Object)]

● in most cases, especially for enterprise applications, data persistence often means saving the data in memory to disk for solidification, while the implementation process of persistence is mostly completed through various relational databases.

● however, there is a word that needs special emphasis here, that is, the so-called "layer". For the application system, the data persistence function is mostly an essential part. In other words, our system has a natural concept of "persistence layer"? Maybe, but maybe that's not the case. The reason why we want to separate the concept of "persistence layer" instead of "persistence module" and "persistence unit" means that there should be a relatively independent logical level in our system architecture, focusing on the implementation of data persistence logic

● this system should have a relatively clear boundary with other systems. [to put it bluntly, it is used to operate the existence of the database!]

1.3 why do you need Mybatis

● Mybatis is to help the program store data in the database and get data from the database

● traditional jdbc operation has many repeated code blocks For example, the encapsulation of data extraction, the establishment and connection of database, etc. through the framework, the repeated code can be reduced and the development efficiency can be improved

● MyBatis is a semi-automatic ORM framework (object relationship mapping) - > object relationship mapping

● all things can still be done without Mybatis, but with it, all the implementation will be easier! There is no distinction between high and low technology, only the people who use it

● advantages of MyBatis

Easy to learn: it is small and simple in itself. There is no third-party dependency. The simplest installation is as long as two jar files + several sql mapping files are configured. It is easy to learn and use. Through documents and source code, you can fully master its design idea and implementation.

Flexibility: mybatis does not impose any impact on the existing design of the application or database. sql is written in xml to facilitate unified management and optimization. All the requirements of operating the database can be met through sql statements.

Decouple sql and program code: separate business logic and data access logic by providing DAO layer, so as to make the design of the system clearer, easier to maintain and easier to unit test. The separation of sql and code improves maintainability.

Provide xml tags to support writing dynamic sql.

Most importantly, many people use it! The company needs!

2. The first mybatis program

Idea: build environment - > Import mybatis - > write code - > test

2.1 construction environment

2.1.1 building database

CREATE DATABASE `mybatis`;

USE `mybatis`;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `user`(`id`,`name`,`pwd`) values (1,'Mad God','123456'),(2,'Zhang San','abcdef'),(3,'Li Si','987654');

2.1.2 import MyBatis related jar packages

● find it on GitHub

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.5.2</version>
</dependency>
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.47</version>
</dependency>

2.1.3. Write MyBatis core configuration file

● view help documents

<?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"/>
           <dataSource type="POOLED">
               <property name="driver" value="com.mysql.jdbc.Driver"/>
               <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
               <property name="username" value="root"/>
               <property name="password" value="123456"/>
           </dataSource>
       </environment>
   </environments>
   <mappers>
       <mapper resource="com/kuang/dao/userMapper.xml"/>
   </mappers>
</configuration>

2.1.4. Write MyBatis tool class

● view help documents

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 sqlSessionFactory;

   static {
       try {
           String resource = "mybatis-config.xml";
           InputStream inputStream = Resources.getResourceAsStream(resource);
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
      } catch (IOException e) {
           e.printStackTrace();
      }
  }

   //Get SqlSession connection
   public static SqlSession getSession(){
       return sqlSessionFactory.openSession();
  }

}

2.1.5. Create entity class

public class User {
   
   private int id;  //id
   private String name;   //full name
   private String pwd;   //password
   
   //Structure, with and without parameters
   //set/get
   //toString()
   
}

2.16. Write Mapper interface class

import com.kuang.pojo.User;
import java.util.List;

public interface UserMapper {
   List<User> selectUser();
}

2.1.7. Prepare mapper XML configuration file

namespace is very important. You can't write it wrong!

<?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.kuang.dao.UserMapper">
 <select id="selectUser" resultType="com.kuang.pojo.User">
  select * from user
 </select>
</mapper>

8. Write test class

Junit package test

public class MyTest {
   @Test
   public void selectUser() {
       SqlSession session = MybatisUtils.getSession();
       //Method 1:
       //List<User> users = session.selectList("com.kuang.mapper.UserMapper.selectUser");
       //Method 2:
       UserMapper mapper = session.getMapper(UserMapper.class);
       List<User> users = mapper.selectUser();

       for (User user: users){
           System.out.println(user);
      }
       session.close();
  }
}

2.1.9. Run the test and successfully query our data, ok!

Summary problem description

Possible problems Description: Maven static resource filtering problem

<resources>
   <resource>
       <directory>src/main/java</directory>
       <includes>
           <include>**/*.properties</include>
           <include>**/*.xml</include>
       </includes>
       <filtering>false</filtering>
   </resource>
   <resource>
       <directory>src/main/resources</directory>
       <includes>
           <include>**/*.properties</include>
           <include>**/*.xml</include>
       </includes>
       <filtering>false</filtering>
   </resource>
</resources>

Keywords: Java Database Mybatis Spring

Added by adrianl on Tue, 08 Mar 2022 14:11:44 +0200