Getting started with mybatis

What is MyBatis?

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. The predecessor was ibatis.
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 POJOs (Plain Old Java Objects) as records in the database through simple XML or annotations.

The first mybatis program

The following figure shows the entire structure, where the classes, xml, etc. are located.

Insert picture description here

Ready to work

Rough process

(1) Create a database and create a table for adding, deleting, modifying and checking.
(2) Create a maven project, and then import the jar package dependencies to be used in pom.xml.
(3) Write the core configuration file of mybatis: mybatis-config.xml.
(4) Write entity classes, UserMapper and UserMapper .xml files.
(5) Encapsulate SqlSessionFactory.
(6) Write test classes.

Note: The mapper is similar to the previous Dao, and the mapper.xml is similar to the implementation class of the previous Dao.
The sequence of the above process is not fixed, as long as it is done.

Specific code

(1) Database

Create a database named mybatis, enter the database

create database mybatis;
use mybatis;

Create user table

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

Insert 3 pieces of data.

insert into user (id, username, pwd) values(1, '张三', '12');
insert into user (id, username, pwd) values(2, '李四', '123');
insert into user (id, username, pwd) values(3, '小明', '1234');

(2) Import the jar package dependency in pom.xml

    <dependencies>
        <!--导入mybatis的jar包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>
        <!--打印日志信息-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--方便测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>

(3) in resourcesthe new package under mybatis-config.xmlthe core document
MyBatis configuration file contains settings and properties that can deeply affect MyBatis behavior. The top-level structure of the configuration document is as follows:

configuration
properties (attributes)
settings (settings)
typeAliases (type aliases)
typeHandlers (type processors)
objectFactory (object factory)
plugins (plug-ins)
environments (environmental configuration)
environment (environmental variables)
transactionManager (transaction manager)
dataSource( Data source)
databaseIdProvider (database vendor identification)
mappers (mapper)

<?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>
    <!--加载编写的db.properties文件-->
    <properties resource="db.properties"/>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--指定mapper接口的映射位置-->
    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>
</configuration>

In order to achieve further separation, the driver, url, username, and password are not written in the core configuration file above, but a tag <properties resource="db.properties"/>that can load the configuration file is added . There is an order, and it should be placed at the top.

Also resourcescreate a new under the package db.propeties, fill in the parameters of driver, url, username and password

driver– This is the fully qualified name of the Java class of the JDBC driver (not the data source class that may be included in the JDBC driver).
url-This is the JDBC URL address of the database.
username– The username for logging in to the database.
password– The password for logging in to the database.

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&characterEncoding=utf-8&serverTimezone=UTC
username=root
password=root

(4) Write entity classes, mapper and mapper.xml files.

The creation of entity class User is a bit long because of the get and set methods. In fact, only those 3 attributes are what I typed by myself.

package com.lu.pojo;

public class User {
    
    

    private int id;

    private String username;

    private String pwd;

    public User() {
    
    
    }

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

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

    public void setPwd(String pwd) {
    
    
        this.pwd = pwd;
    }

    public int getId() {
    
    
        return id;
    }

    public String getUsername() {
    
    
        return username;
    }

    public String getPwd() {
    
    
        return pwd;
    }

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

Create UserMapper , similar to the previous dao layer, and write some interfaces.
The location can be placed in the mapper folder, and it is convenient to manage if there are more in the future

package com.lu.mapper;

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

public interface UserMapper {
    
    

    /**
     * 查询所有用户
     */
    List<User> findAll();
}

Create a UserMapper.xml file , similar to the previous daoimpl layer, to implement the interface in the mapper.
For the location, you can create a mapper folder under resource, and then put it inside, just like the picture at the beginning; it can also be placed on the mapper layer, you need to add filtering in the core configuration file, so that the program can recognize these xml.

In UserMapper.xml below, namespace writes the UserMapper interface to be implemented, and the full name is written; id writes a certain class of the interface; resultType is the returned result type, write the full name.

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

(5) Encapsulate SqlSessionFactory.

package com.lu.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";
            //创建SqlSessionFactory的构建者对象
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //创建工厂对象
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        }catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
    //获取SqlSession实例,其包含了面向数据库执行SQL命令所需的所有方法
    public static SqlSession getSqlSession() {
    
    
        return sqlSessionFactory.openSession();
    }
}

(6) Write test classes.

package com.lu.test;

import com.lu.mapper.UserMapper;
import com.lu.pojo.User;
import com.lu.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import java.util.List;

public class MybatisTest {
    
    
    public static void main(String[] args) {
    
    
        //通过封装的MybatisUtils类获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //使用SqlSession创建dao接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        //使用代理对象执行查询所有方法
        List<User> users = userMapper.findAll();
        for (User user : users) {
    
    
            System.out.println(user);
        }
    }
}

Next article: Realization of additions, deletions and modifications and annotations

Log warning and simple use

The first few lines will be red after running, but it does not affect. But it can also be solved.
In the resourcenext creationlog4j.properties

#指定日志的输出级别与输出端
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# 输出日志到控制台,以下设置分别为控制台,布局格式,布局显示样式
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# 输出日志到文件
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:/axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

Simple to use

After importing the maven coordinate dependency and writing the log4j.properties file, you can use and output information to the console.
1. Import in the class to use Log4j

  import org.apache.log4j.Logger;

2. Log object, the parameter is the class of the current class.

  static Logger logger = Logger.getLogger(MybatisTest.class);

3. Log level

logger.info("查询成功");
logger.debug("111");
logger.error("1222");

Scope and life cycle

SqlSessionFactoryBuilder

Scope: partial method
life cycle: useless once used

Official document: This class can be instantiated, used and discarded. Once the SqlSessionFactory is created, it is no longer needed. Therefore, the best scope of the SqlSessionFactoryBuilder instance is the method scope (that is, local method variables). You can reuse SqlSessionFactoryBuilder to create multiple SqlSessionFactory instances, but it is better not to keep it all the time to ensure that all XML parsing resources can be released for more important things.

SqlSessionFactory
scope: application scope
life cycle: it always exists during application operation after creation

Official document: Once the SqlSessionFactory is created, it should always exist during the running of the application. There is no reason to discard it or recreate another instance. The best practice for using SqlSessionFactory is not to recreate it multiple times during the running of the application. Rebuilding the SqlSessionFactory multiple times is regarded as a code "bad habit". Therefore, the best scope of SqlSessionFactory is the application scope. There are many ways to do it, the easiest is to use singleton mode or static singleton mode.

SqlSession
scope: request or method scope
life cycle: after returning a response, close it

Official document: Each thread should have its own SqlSession instance. The instance of SqlSession is not thread-safe, so it cannot be shared, so its best scope is the request or method scope. Never put the reference of the SqlSession instance in the static domain of a class, even the instance variables of a class. Never place the reference of the SqlSession instance in any type of managed scope, such as HttpSession in the Servlet framework. If you are currently using a web framework, consider placing SqlSession in a scope similar to HTTP requests. In other words, every time you receive an HTTP request, you can open a SqlSession, and close it after returning a response. This close operation is very important. In order to ensure that the close operation can be executed every time, you should put this close operation in the finally block.

Guess you like

Origin blog.csdn.net/qq_42524288/article/details/108593021