Take you hand in hand to implement the first mybatis program

Time:2021-10-12

Environmental description:

JDK 13mysql 8.0.22maven 3.8.1 development tool: Idea

Before learning, you need to master:

JDBC MySQL Java foundation Maven JUnit

What is mybatis?

Mybatis is an excellent persistence layer framework. Mybatis avoids almost all JDBC codes 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. Migrated to GitHub. Mybatis in November 2013. Official document: http://www.mybatis.org/mybatis-3/zh/index.htmlGitHub : 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.

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. Therefore, even if the object does not need to be permanently saved, it will not stay in memory all the time due to the capacity limit of memory, and it needs to be persisted to cache to external memory.

Persistent layer

What is persistence layer?

Code block to complete persistence. — > Dao layer [Dao (data access object) data access object] in most cases, especially enterprise applications, data persistence often means saving the data in memory to disk for solidification, and the implementation process of persistence is mostly completed through various relational databases. However, there is a word that needs special emphasis, that is, the so-called “layer”. For application systems, data persistence is 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 a “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 relatively 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, such as the encapsulation of data extraction, the establishment of database connection, 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 difference between high and low technology, only the people who use it

Advantages of mybatis

Easy to learn: itself is small and simple. There is no third-party dependency. The simplest installation is just two jar files + several SQL mapping files. 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 for unified management and optimization. All requirements for operating the database can be met through SQL statements. Decouple SQL and program code: by providing Dao layer, separate business logic and data access logic, so as to make the system design 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!

Mybatis first program

Build experimental database

Create a MySQL database in mysql, use it as a test database, create a user table, and initialize several pieces of data

Create table SQL statement


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,'qifei','123456'),(2,'chuachua','123456'),(3,'pig','111');

Import mybatis related jar package

Create a new Maven project and import the basic framework and drivers into the pom.xml file.

image

Dependency:


<dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

Write mybatis core configuration file

View the help documentation and write the mybatis core configuration file.

image

在这里插入图片描述

Write mybatis tool class

Each mybatis based application takes an instance of sqlsessionfactory as the core. An instance of sqlsessionfactory can be obtained through sqlsessionfactorybuilder. Sqlsessionfactory builder can build a sqlsessionfactory instance from an XML configuration file or a pre configured configuration instance.

Building an instance of sqlsessionfactory from an XML file is very simple. It is recommended to use the resource file under the classpath for configuration. However, you can also use any input stream instance, such as an input stream constructed with a file path string or a file: / / url. Mybatis contains a tool class called resources, which contains some practical methods to make it easier to load resource files from the classpath or other locations.

Now that we have sqlsessionfactory, as the name suggests, we can get an instance of sqlsession from it. Sqlsession provides all the methods required to execute SQL commands in the database.

image

MybatisUtils.java:

package com.luckylazypig.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 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();
    }
}

Create entity class

Create an entity class to receive fields in the database. Private variables must correspond to database table field names one by one.

image

User entity class


package com.luckylazypig.pojo;
public class User {
    private int id;
    private String name;
    private String pwd;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

Writing mapper interface classes

Writing mapper interface classes

image

UserMapper.java:


package com.luckylazypig.dao;
import com.luckylazypig.pojo.User;
import java.util.List;
public interface UserMapper {
    List<User> selectUser();
}

Write mapper.xml configuration file

Namespace: corresponds to the interface you want to materialize. ID: corresponds to the abstract method you want to instantiate. Resulttype: corresponds to your return type object. The object name is the qualified object name

image


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

Writing test classes

image

Test class code:


package com.luckylazypig.dao;
import com.luckylazypig.pojo.User;
import com.luckylazypig.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
    @Test
    public void selectUser(){
        SqlSession session = MybatisUtils.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> users = mapper.selectUser();
//        List<User> users = session.selectList("com.luckylazypig.dao.UserMapper.selectUser");
        for (User user : users) {
            System.out.println(user);
        }
        session.close();
    }
}

Maven static resource filtering

Possible problem description: Maven static resource filtering problem

image

Configuration code:


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

summary

That’s all for this article. I hope it can help you and pay more attention to developeppaer!

Recommended Today

The selector returned by ngrx store createselector performs one-step debugging of fetching logic

Test source code: import { Component } from ‘@angular/core’; import { createSelector } from ‘@ngrx/store’; export interface State { counter1: number; counter2: number; } export const selectCounter1 = (state: State) => state.counter1; export const selectCounter2 = (state: State) => state.counter2; export const selectTotal = createSelector( selectCounter1, selectCounter2, (counter1, counter2) => counter1 + counter2 ); // […]