[Mybatis1] Introduction and quick start

Article directory

 Mybatis overview

persistence layer

frame

 Comparison between Mybatis and JDBC

 JDBC code flaws

 Mybatis simplifies JDBC

 Mybatis quick start case

Overall case project structure

 1. Create user table and add data

 2. Create a Maven project and import coordinates

3. Write the Mybatis core configuration file

 4. Write the entity class of the database return object

5. Write SQL mapping file

6. Test class usage

7. Query results

 Summarize


 Mybatis overview

        Mybatis is an excellent persistence layer framework , used to simplify the development of previous versions of JDBC to improve development efficiency and maintainability.

persistence layer

  • The layer of code responsible for saving data to the database, we will use the Java code that operates the database as the persistence layer.
  • JavaEE three-tier architecture: presentation layer, business layer, persistence layer

frame

  • A framework is a semi-finished software , a set of reusable, universal, software basic code models.
  • Building software based on the framework is more efficient, standardized, universal and scalable

        As shown in the figure below, blank plaster is equivalent to a framework. Developers "painting different colors" on it to build different dolls are equivalent to secondary development based on the framework. This is the popular understanding of using frameworks to develop software.


 Comparison between Mybatis and JDBC

 JDBC code flaws

 Mybatis simplifies JDBC


 Mybatis quick start case

Overall case project structure

The following is a step-by-step introduction to the Mybatis quick start case: database query

 1. Create user table and add data

create database mybatis;
use mybatis;

drop table if exists tb_user;

create table tb_user(
	id int primary key auto_increment,
	username varchar(20),
	password varchar(20),
	gender char(1),
	addr varchar(30)
);

INSERT INTO tb_user VALUES (1, 'Aricl.', '123', '男', '盐城');
INSERT INTO tb_user VALUES (2, '小钱', '456', '女', '南京');
INSERT INTO tb_user VALUES (3, '小王', '789', '男', '苏州');

 

 2. Create a Maven project and import coordinates

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>mybatis-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>


    <dependencies>

        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <!-- mysql 驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <!-- 添加slf4j日志api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.20</version>
        </dependency>
        <!-- 添加logback-classic依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- 添加logback-core依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>

    </dependencies>

</project>

Create the logback.xml file under the resources resource folder. It is mainly used for console printing logs with clear colors for easy viewing.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--
        CONSOLE :表示当前的日志信息是可以输出到控制台的。
    -->
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
        </encoder>
    </appender>

    <logger name="com.itheima" level="DEBUG" additivity="false">
        <appender-ref ref="Console"/>
    </logger>


    <!--

      level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
     , 默认debug
      <root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。
      -->
    <root level="DEBUG">
        <appender-ref ref="Console"/>
    </root>
</configuration>

3. Write the Mybatis core configuration file

 Replace connection information to solve JDBC hard-coding problem

mybatis-config.xml

<?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">
<!--                数据库连接信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
<!--    加载sql映射文件-->
    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

 4. Write the entity class of the database return object

User.java

package itheima;

public class User {
//    快捷键:ALT+鼠标左键=>整列编辑
    private Integer id            ;
    private String username      ;
    private String password      ;
    private String gender        ;
    private String addr          ;

    public User(Integer id, String username, String password, String gender, String addr) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.gender = gender;
        this.addr = addr;
    }

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

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

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

    public void setGender(String gender) {
        this.gender = gender;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    public Integer getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getGender() {
        return gender;
    }

    public String getAddr() {
        return addr;
    }

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

5. Write SQL mapping file

 Unified management of SQL statements to solve JDBC hard coding problems

UserMapper.xml

<?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-test">
    <select id="selectAllUser" resultType="itheima.User">
       select * from tb_user
    </select>
</mapper>

6. Test class usage

package itheima;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import javax.annotation.Resources;
import java.io.InputStream;
import java.io.IOException;
import java.util.List;

import static javax.annotation.Resources.*;
import static org.apache.ibatis.io.Resources.getResourceAsStream;
/**
 * Mybatis快速入门案例
 */
public class MybatisDemo {
    public static void main(String[] args) throws IOException{
        //1.加载mybatis的核心配置文件,获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.执行sql,将查询到的学生数据以学生类的形式包装起来返回
        List<User> users=sqlSession.selectList("Mybatis-test.selectAllUser");
        System.out.println(users);
        //4.释放资源
        sqlSession.close();
    }
}

7. Query results


 Summarize

        JDBC, as the most primitive way to operate databases, has a lot of hard coding , that is, strings are hard-coded and cannot be modified dynamically. When there are many data fields and SQL statements, it will be particularly troublesome and time-consuming to modify once there are many data fields and SQL statements .

        In addition, the processing of result sets is fixed. When there are many fields, using JDBC will write a lot of repetitive and non-technical code, which is a waste of time.

        Mybatis has optimized and improved the above defects. It writes the data connection information and SQL statements into the configuration file, and the operation of the result set is completed in one line of code by calling the encapsulated method. This greatly simplifies the tedious aspects of the previous JDBC and enhances the Code maintainability , in summary: Mybatis is indeed a very excellent persistence layer framework, worthy of its name!

References

Mybatis official documentation https://mybatis.org/mybatis-3/zh/getting-started.html

 

 END. 

Guess you like

Origin blog.csdn.net/qq_52487066/article/details/129349384