Complete solution of mybatis series (2): introduction to mybatis and environment construction

Time:2021-2-18

Cover: Luo Xiaoxi
Author: Pan Pan

Complete solution of mybatis series (2): introduction to mybatis and environment construction

Complete solution of mybatis series (2): introduction to mybatis and environment construction

Mybatis is a set of persistence layer framework, flexible and easy to use, especially popular.

Complete solution of mybatis series (2): introduction to mybatis and environment construction

preface

We expect to prepare 10 + articles to let us know the basic panorama of mybatis, from the beginning to the beginning, from the beginning to the mastery. The first part of this article, let’s begin.

Complete solution of mybaits series (continuous update)

  • Complete solution of mybatis series (1): a persistence layer framework
  • Complete solution of mybatis series (2): introduction to mybatis and environment construction
  • Complete solution of mybatis series (3): introduction to mybatis CRUD
  • Mybatis series complete solution (4): the most complete network! Detailed explanation of mybatis configuration file XML
  • Mybatis series (5): the most complete network! Detailed explanation of mapper mapping file of mybatis
  • Complete solution of mybatis series (6): how many of the most hard core API of mybatis do you know?
  • The complete solution of mybatis series (7): the traditional way and proxy way of Dao layer from the perspective of holography
  • Complete solution of mybatis series (8): dynamic SQL of mybatis
  • Complete solutions of mybatis series (9): complex mappings of mybatis
  • Complete solution of mybatis series (10): development of mybatis annotation
  • Complete solution of mybatis series (11): complete solution of mybatis cache
  • Mybatis plug in development
  • Complete solution of mybatis series (13): mybatis code generator
  • Complete solution of mybatis series (14): Spring integrates mybatis
  • Complete solution of mybatis series (15): integration of springboot and mybatis
  • Mybatis series complete solution (16): mybatis source code analysis

catalog

1. What is mybatis

2. Mybatis: past and present

3. Advantages of mybatis

4. Overall architecture of mybatis

5. Environment construction

6. Summary

Complete solution of mybatis series (2): introduction to mybatis and environment construction

What is mybatis

Let’s take a look at the official website of mybatis https://mybatis.org/mybatis-3/

MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.

It can be roughly translated as:

Mybatis is an excellent persistence layer framework, which supports customized SQL, stored procedures and advanced mapping. Mybatis avoids almost all JDBC code and manual setting of parameters and obtaining result sets. Mybatis can use simple XML or annotations to configure and map native types, collection interfaces, and Java POJO (plain old Java objects) as records in the database.

My current understanding is that mybatis abstracts a lot of JDBC redundant code, and provides a set of flexible and easy-to-use API to interact with database based on object relational mapping model.

Complete solution of mybatis series (2): introduction to mybatis and environment construction

Mybatis: past and present

Everything has a past. We talked about it beforeJDBCThe differences between JDBC and persistence layer framework are analyzed and compared. Because JDBC requires developers to write too much code and operate all objects, it is troublesome and easy to make mistakes, so we seldom use JDBC to program directly in our actual developmentORMThe full name of ORM is object / relationship mappingObject relation mappingThe abbreviation for.

Complete solution of mybatis series (2): introduction to mybatis and environment construction

ORM modelTo put it simply, it is the mapping relationship model of database tables and simple Java objects. After adopting ORM framework, the application program no longer directly accesses the underlying database, but uses theobject-orientedThe ORM framework transforms these object-oriented operations into the underlying SQL operations. ORM framework to achieve the effect: the persistent object to save, modify, delete and other operations, converted to database operations.

Complete solution of mybatis series (2): introduction to mybatis and environment construction

At first, Sun company introduced Java EE server-side component model(EJB)However, due to the complexity of EJB configuration and the small adaptation range, EJB will soon be eliminated. Later, ORM persistence layer framework with high encapsulation, high efficiency and full table mapping was developedHibernateAt that time, it became the preferred Java ORM model framework. However, with the rapid development of the Internet and the emergence of complex business scenarios, hibernate has gradually exposed its shortcomings in many aspects: insufficient flexibility, unable to assemble different SQL according to different conditions, poor support for multi table Association and complex SQL query, poor SQL optimization and performance, inconvenience caused by full table mapping, etc.

Complete solution of mybatis series (2): introduction to mybatis and environment construction

thereforeMybatisFramework emerges as the times require, which makes up for the lack of hibernate. It is not only simple and easy to use, but also has the characteristics of high flexibility, optimization and easy maintenance. It has become the preferred framework for large-scale Internet projects.

Mybatis unofficial history: mybatis, formerly known as ibatis, was an open source project initiated by Clinton begin in 2001. It initially focused on the development of cryptographic software, and later developed into a persistence layer framework based on Java. In 2004, Clinton donated the name and source code of ibatis to Apache Software foundation. In the next six years, great changes have taken place in the world of open source software. All development practices, infrastructure, licensing and even database technology have changed completely. In June 2010, the core development team migrated the project from Apache Software Foundation to Google Code. With the development team switching to Google Code, ibatis3. X was officially renamed mybatis, and the code was migrated to GitHub in November 2013.

Complete solution of mybatis series (2): introduction to mybatis and environment construction

Advantages of mybatis

Mybatis is a semi-automatic persistence layer framework. For developers, the core SQL still needs to be optimized by themselves. SQL and Java coding are separated. The functional boundary is clear. One focuses on business and the other focuses on data.

The blue area is the function support of mybatis framework, and the red area is the two steps of the actual operation of the engineering project applying mybatis framework

Complete solution of mybatis series (2): introduction to mybatis and environment construction

Currently, there are many persistence frameworks implemented by Java, but mybatis is popular for the following reasons:

1. It eliminates a lot of redundant JDBC code

2. It has a low learning curve

3. It can work well with traditional database

4. It can accept SQL statements

5. It provides integration support with spring and Guice frameworks

6. It provides integration support with third-party cache class libraries

7. It introduces better performance

Complete solution of mybatis series (2): introduction to mybatis and environment construction

Overall architecture of mybatis

Complete solution of mybatis series (2): introduction to mybatis and environment construction

Complete solution of mybatis series (2): introduction to mybatis and environment construction

Environment construction

Java development environment, MySQL database and Maven environment are installed by default.

For mybatis development and environment construction, let’s start with the following steps:

1. Create Maven project

2. Add coordinates of mybatis warehouse (jar package will be introduced for non Maven projects)

3. Create user data table

4. Write user entity class

5. Write mapping file UserMapper.xml

6. Writing core documents SqlMapConfig.xml

7. Write test class

1. Create Maven project

Complete solution of mybatis series (2): introduction to mybatis and environment construction

2. Add mybatis warehouse coordinates

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

        <! -- mybatis coordinates -- >
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

        <! -- MySQL drive coordinates -- >
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
            <scope>runtime</scope>
        </dependency>

        <! -- unit test coordinates -- >
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <! -- log coordinates -- >
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>

    </dependencies>

3. Create user data table


CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  `birthday` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

Complete solution of mybatis series (2): introduction to mybatis and environment construction

4. Write user entity class

package com.panshenlian.pojo;

/**
 * @Author: panshenlian
 *@ Description: user entity
 * @Date: Create in 2:08 2020/11/28
 */
public class User {
    private int id;
    private String username;
    private String password;
    private String birthday;

    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday='" + birthday + '\'' +
                '}';
    }
}

5. Write mapping file UserMapper.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">
<mapper namespace="userMapper">

    <select id="findAll" resultType="com.panshenlian.pojo.User">
        select * from User
    </select>

</mapper>

6. Writing core documents SqlMapConfig.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>
    <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" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="/UserMapper.xml" />
    </mappers>
</configuration>

7. Write test class

package com.panshenlian.service;

import com.panshenlian.pojo.User;
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;
import java.util.List;

/**
 * @Author: panshenlian
 *@ Description: experience test class
 * @Date: Create in 2:21 2020/11/28
 */
public class MybatisTest {

    @Test
    public void testQueryUser01() throws IOException {

        //Load core profile
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");

        //Get the sqlsession factory object
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        //Get the sqlsession object
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //Execute SQL statement
        List<User> userList = sqlSession.selectList("userMapper.findAll");

        //Print results
        for (User user : userList) {
            System.out.println(user);
        }

        //Release resources
        sqlSession.close();
    }


}

Complete solution of mybatis series (2): introduction to mybatis and environment construction
Finally, through JUnit unit test, the running results meet the expectations

Complete solution of mybatis series (2): introduction to mybatis and environment construction

Complete solution of mybatis series (2): introduction to mybatis and environment construction
Engineering structure reference:

Complete solution of mybatis series (2): introduction to mybatis and environment construction

Complete solution of mybatis series (2): introduction to mybatis and environment construction

summary

Through the introduction of this article, we also started to do a test project of the entry experience, and basically had a preliminary understanding of mybatis. At the same time, we compared JDBC with hibernate, and clarified the mission of the birth of mybatis and its inherent advantages and capabilities. In the future, we will continue to explain in depth and sort out and analyze the various knowledge threads of mybatis.

At the end of this article, we will talk about the next article in this series《Introduction to mybatis CRUD 》。

Complete solution of mybatis series (2): introduction to mybatis and environment construction

Complete solution of mybatis series (2): introduction to mybatis and environment construction

BIU ~Articles are continuously updated, wechat search “Pan and his friends“The first time to read, there are always surprises. This article will be published inGitHubhttps://github.com/JavaWorld Included, hot technology, framework, face-to-face, solutions, we will be the first time to deliver the most beautiful posture, welcome star.