Notes on the mybatis framework

Posted by russlock on Sat, 05 Mar 2022 09:39:45 +0100

Note: This article is a note taken following the mybatis course of crazy God talking about java. Don't spray it if you don't like it!

Link to mybatis Video: [crazy God says Java] the latest complete tutorial of Mybatis, the IDEA version is easy to understand_ Beep beep beep_ bilibili

What is MyBatis

  • MyBatis is an excellent persistence layer framework

  • MyBatis avoids almost all JDBC code and the process of manually setting parameters and obtaining result sets

  • MyBatis can use simple XML or annotations to configure and map native information, and map the interface and Java entity class [Plain Old Java Objects] into records in the database.

  • MyBatis was originally an open source project ibatis of apache. In 2010, this project was migrated from apache 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

Persistence

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

  • That is to save data (such as objects in memory) to a permanent storage device (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 memory power failure, but some objects cannot be lost anyway, such as bank accounts. Unfortunately, people can't guarantee that memory will never power down.

  • 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. The object does not need to be stored in the external memory even if it is stored in the external memory.

Persistent layer

What is persistence layer?

  • A block of code that completes the persistence work ---- > 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 one word that needs special emphasis, 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

  • Compared with other parts of the system, this level should have a clear and strict logical boundary. [to put it bluntly, it is used to operate the existence of the database!]

Why do you need Mybatis

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

  • The traditional jdbc operation has many repeated code blocks For example: encapsulation of data extraction, establishment and connection of database, etc, The framework can reduce repeated code and improve development efficiency

  • 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!

Next, let's start writing our first mybatis!!!

Thought process: build environment -- > Import mybatis -- > write code -- > test

The project structure is as follows:

 

First, the steps to use mybatis from 0 are as follows:

1. Build experimental 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. Mytis package import

POM in the parent project of idea Add dependency in XML and add mysql driver and jar package of mybatis

  • 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>

3. Write MyBatis core configuration file

Create an xml file named mybatis config. In the resources of the subproject xml (the specification is this, which can also be ignored). Then write the following code in it and change it to your own mysql connection variable. Finally, the variable in mappers means that your mappers need to be registered in it before they can be used

  • View help documentation

<?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;characterEncoding=UTF-8&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!-- every last mapper.xml All need to be in mybatis Core profile registration   -->
    <mappers>
        <mapper resource="com/xiong/dao/UserMapper.xml"/>
    </mappers>
</configuration>

4. Write MyBatis tool class

  • View help documentation

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();
  }

}

5. Create entity class

Create a class to connect with the database table, and use this object to "connect" each piece of data.

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

6. Write Mapper interface class

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

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

7. Write mapper XML configuration file

  • namespace is very important. You can't write it wrong! (assign to mapper)

  • resultType specifies the return type

  • sql statements are written in select

<?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");

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

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

Problem description

Possible problems Description: Maven static resource filtering problem

If it doesn't work, it's in PRM Add this line of code to XML

   <build>
        <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>
    </build>

Possible problems:

1. The configuration file is not registered (mapper.xml is not registered in the core configuration file)

2. Binding interface error. (interface error in namespace)

3. Wrong method name (wrong id of select in mapper.xml)

4. Wrong return type (resultType error)

5.maven export resources

Review what you did throughout:

1. Import the jar package, create the project, and then import the jar package of mysql driver and mybatis

2. Write a core configuration file of mybatis in the resource, and then change the mysql connection and if there is a mapper XML, we need to register mapper

3. For the required sqlSessionFactory, we created a tool class and obtained the factory, so we need to create a connection, so we wrote a tool class to obtain the connection

4. We write an entity class object User to "pick up" every piece of data.

5. After the entity class is written, we will write the interface

6. Then we write mapper. In jdbc, we write an implementation class. Instead of the mapper class, we write the file now. How to write mapper? We first bind the interface in the namespace, then bind the method in the tag id, then write sql in the tag body, and then write our entity class in its return value type (tag resultType).

7. Just adjust the method directly during the final test. How to write the test? The first step is to get the sqlsession object, use the tool class we wrote to get the sqlSessionFactory, and then get it. The second step is to use getMapper of sqlsession. The parameter is UserDao class, return a UserDao, and then call the methods inside

Topics: Java Maven intellij-idea