[MyBatis Series ①] Addition, deletion, modification and query

Table of contents

1. Basic review

2. Example introduction

3. Mapping file

4. CRUD

4.1、add

4.2、delete

4.3、update

4.4、check

5. Core configuration file

5.1、properties

5.2、typeAliases

5.2.1. Customization

5.2.2, ⭐MyBatis comes with

5.3、environments

5.3.1、environment

5.3.2、transactionManager

5.3.3、dataSource

5.4、 mapper

6、API

6.1、SqlSessionFactoryBuilder

6.2、SqlSessionFactory

6.3、SqlSession


1. Basic review

MyBatis Basics: Java Web - MyBatis

Here are a few pictures to briefly review:

Raw JDBC query operation:

Raw JDBC insert operation:

2. Example introduction

For the specific operation of MyBatis, here is a small example to get started quickly:

Prepare the environment as follows:

①Create Maven Model and introduce coordinates in pom.xml

pom.xml

The most important thing is mybatis and mysql coordinates:

The overall pom file is as follows:

<?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</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>8080</port>
                    <uriEncoding>UTF-8</uriEncoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <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>
            <scope>runtime</scope>
        </dependency>
        <!--单元测试坐标-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--日志坐标-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
    </dependencies>
</project>

Initialize the database

SQL statements:

CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE user(
        id INT(11) NOT NULL AUTO_INCREMENT,
        username VARCHAR(50),
        password VARCHAR(50),
        PRIMARY KEY(id)
);
DESCRIBE user;

Write the User entity class

package com.xzl.domain;

/**
 * @author 逐梦苍穹
 * @date 2023/8/23 17:44
 */
public class User {
    private int id;
    private String username;
    private String password;

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

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

Write the core configuration file mybatis-config.xml

<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--通过properties标签加载外部properties文件-->
    <properties resource="jdbc.properties"/>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/xzl/domain/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

⑤Write the SQL mapping file UserMapper.xml (this part of the code will change later, and it will remain unchanged here)

test

Here, for the convenience of testing, a log4j logging framework is also needed (Logback can also be used):

log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=debug, stdout

MyBatisTest

/**
 * @author 逐梦苍穹
 * @date 2023/8/23 23:21
 */
public class MyBatisTest {
    @Test
    public void findAll_test1() throws IOException {
        //加载核心配置文件
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        //获得sqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //获得sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //执行sql语句
        List<User> userList = sqlSession.selectList("userMapper.findAll");
        //打印结果
        System.out.println(userList);
        //释放资源
        sqlSession.close();
    }
}

Test Results:

3. Mapping file

4. CRUD

Operations that involve modifying database content must submit transactions manually! ! mybatis does not commit transactions by default

Basic process:

        Load the core configuration file

        Get the sqlSession factory object

        Get the sqlSession object

        execute sql statement

        (commit transaction)

        release resources

Extract the first three steps:

4.1、add

Java code:

Mapping file:

This involves a primary key self-increment problem. If there is no way to encapsulate the object, the method of executing first and then encapsulating is used . The example is as follows:

Precautions:

  1. The insert statement uses the insert tag
  2. Use the parameterType attribute in the mapping file to specify the type of data to be inserted
  3. In the Sql statement, use #{entity attribute name} to refer to the attribute value in the entity
  4. The API used by the insert operation is sqlSession.insert("namespace.id", entity object);
  5. The insert operation involves database data changes, so use the commit transaction displayed by the sqlSession object, that is, sqlSession.commit()

4.2、delete

Java code:

Mapping file:

Precautions:

  1. Delete statements use the delete label
  2. In the Sql statement, use #{arbitrary string} to refer to the passed single parameter
  3. The API used by the delete operation is sqlSession.delete("namespace.id", Object);

4.3、update

Java code:

Mapping file:

Precautions:

  1. Modify the statement using the update tag
  2. The API used by the modification operation is sqlSession.update("namespace.id", entity object);

4.4、check

5. Core configuration file

configuration item

describe

configuration

The root element, containing the main part of the entire configuration

properties

Define the attribute value, and then reference it in the configuration

settings

Configure global settings for MyBatis

typeAliases

Define an alias for a Java type

typeHandlers

Configure custom type handlers

objectFactory

Specifies the class name of the object factory

plugins

Configure custom plugins

environments

Configure different database environments

environment

Inside the environments , define the specific database environment

transactionManager

Specifies the type of transaction manager

dataSource

Configure the data source for the database connection

databaseIdProvider

Configure SQL statements and syntax for different databases

mappers

Specify the location of the mapper (Mapper)

5.1、properties

In actual development, it is customary to extract the configuration information of the data source separately into a properties file, which can load additionally configured properties files

5.2、typeAliases

5.2.1 , Custom

A type alias is to set a name for a Java type to simplify the amount of code.

turn out to be:

Set an alias in mybatis-config.xml:

After setting the alias:

5.2.2 MyBatis comes with

The above is a custom alias, and the mybatis framework has already set up some common types of aliases:

alias

The corresponding Java type

string

java.lang.String

byte

java.lang.Byte

long

java.lang.Long

short

java.lang.Short

int

java.lang.Integer

integer

java.lang.Integer

double

java.lang.Double

float

java.lang.Float

boolean

java.lang.Boolean

char

java.lang.Character

character

java.lang.Character

date

java.util.Date

decimal

java.math.BigDecimal

bigdecimal

java.math.BigDecimal

big integer

java.math.BigInteger

object

java.lang.Object

list

java.util.List

arraylist

java.util.ArrayList

map

java.util.Map

hashmap

java.util.HashMap

5.3、environments

Configure different database environments (e.g. development, test, production)

5.3.1、environment

Support multi-environment configuration:

5.3.2、transactionManager

There are two types of transaction managers:

①JDBC: This configuration uses the commit and rollback settings of JDBC directly, and it relies on the connection obtained from the data source to manage the transaction scope.

②MANAGED: This configuration does almost nothing. It never commits or rolls back a connection, but lets the container manage the entire life cycle of the transaction (such as the context of the JEE application server). By default it closes the connection, however some containers don't want this, so you need to set the closeConnection property to false to prevent it from closing by default.

5.3.3、dataSource

There are three types of data sources:

①UNPOOLED: The implementation of this data source just opens and closes the connection each time it is requested.

②POOLED: The implementation of this data source uses the concept of "pool" to organize JDBC connection objects.

③JNDI: The implementation of this data source is to be used in containers such as EJB or application server. The container can configure the data source centrally or externally, and then place a reference to the JNDI context.

5.4、 mapper

该标签的作用是加载映射的,加载方式有如下几种:

①使用相对于类路径的资源引用,例如:

<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>

②使用完全限定资源定位符(URL),例如:

<mapper url="file:///var/mappers/AuthorMapper.xml"/>

③使用映射器接口实现类的完全限定类名,例如:

<mapper class="org.mybatis.builder.AuthorMapper"/>

④将包内的映射器接口实现全部注册为映射器,例如:

<package name="org.mybatis.builder"/>

6、API

6.1、SqlSessionFactoryBuilder

SqlSessionFactory build(InputStream inputStream) 通过加载mybatis的核心文件的输入流的形式构建一个SqlSessionFactory对象

其中, Resources 工具类,这个类在 org.apache.ibatis.io 包中。

Resources 类帮助开发者从类路径下、文件系统或 一个 web URL 中加载资源文件。

6.2SqlSessionFactory

SqlSessionFactory 有多个个方法创建 SqlSession 实例。常用的有如下两个:

方法

解释

openSession()

会默认开启一个事务,但事务不会自动提交,

This means that the transaction needs to be submitted manually, and the update operation data will be persisted in the database

openSession(boolean autoCommit)

The parameter is whether to submit automatically, if set to true,

Then there is no need to manually commit the transaction

6.3、SqlSession

The SqlSession instance is a very powerful class in MyBatis.

Here you'll see all the methods to execute statements, commit or rollback transactions, and get mapper instances.

The main methods of executing statements are:

The main methods of operating transactions are:

Guess you like

Origin blog.csdn.net/qq_60735796/article/details/132463853