[MyBatis series ④] Core configuration file

Table of contents

1 Introduction

2、DTD

3、typeHandlers

3.1, default type processor

3.2, custom type processor

4、plugins


⭐MyBatis series ①: add, delete, modify and check

⭐MyBatis Series②: Two Dao development methods

⭐MyBatis Series③: Dynamic SQL

1. Introduction

The core configuration file of MyBatis (usually named mybatis-config.xml) is one of the important files to configure the MyBatis framework.

It defines global settings, including database connection information, object-relational mapping (ORM) settings, plugin configuration, type handlers, and more.

The documentation states:

This part is used to declare the document type definition (DOCTYPE) of the MyBatis core configuration file. It tells the XML parser how to interpret this XML file. The content is explained as follows:

  1. <!DOCTYPE configuration : This part indicates that this is a document type declaration, which specifies the type of document as configuration , which is the core configuration file of MyBatis.
  2. PUBLIC "-//mybatis.org//DTD Config 3.0//EN" : This is an identifier used to specify the public identifier (Public Identifier) ​​of the document type. Here, -//mybatis.org//DTD Config 3.0//EN specifies the version and language of the MyBatis configuration file.
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd" : This is the system identifier (System Identifier) ​​defined by the document type, which specifies the location of the DTD file. In this example, it points to the URL of the DTD (Document Type Definition) file of the MyBatis configuration file.

Taken together, this document type declaration tells the XML parser how to interpret the XML file, as well as the version and location of the DTD specification that the XML file follows. Here, it specifies that the version of the MyBatis core configuration file is 3.0, and uses the official DTD file provided by MyBatis for parsing.

2、DTD

This XML file is a DTD (Document Type Definition) document, which is used to define the core configuration file structure and element specifications of MyBatis. This DTD file describes the elements, attributes and relationships between them that can be used in MyBatis configuration files.

The comments and tags in this DTD file explain the meaning of each element, attributes and sub-elements.

element

describe

configuration

The root element represents the configuration information of MyBatis, including database connection, mapper configuration, etc.

databaseIdProvider

The database ID provider element is used to provide different configurations for different databases.

properties

Properties element, used to set global properties, can be loaded from external resources.

property

The attribute element, with name and value attributes, is used to define the name and value of the attribute.

settings

Settings element, used to define global settings.

setting

A single settings element, with name and value attributes.

typeAliases

The type alias element is used to define an alias for a Java class.

typeAlias

Type alias element, with type and alias attributes, used to define type alias.

typeHandlers

Type processor element, used for custom type processors.

typeHandler

Type handler element, with javaType, jdbcType and handler attributes.

objectFactory

Object factory elements for customizing how objects are created.

objectWrapperFactory

Object wrapper factory element for custom object wrappers.

reflectorFactory

Reflector factory element for customizing reflectors.

plugins

Plugin element for adding plugin interceptors.

plugin

The plug-in element, with the interceptor attribute, specifies the class name of the plug-in interceptor.

environments

A database environment element that defines a transaction manager and data source.

environment

The environment element, with an id attribute, is used to define a database environment.

transactionManager

A transaction manager element that defines a transaction manager type.

dataSource

Data source element, used to define the data source type.

mappers

A mapper element to define a mapper configuration.

mapper

A mapper element, with resource, url, and class attributes, used to define the location of the mapper file.

package

Package element, used to define a Java package.

This DTD file describes the various elements and attributes that can be used in the MyBatis core configuration file, helping developers write configuration files that conform to the specification.

3、typeHandlers

typeHandlers is an element in the MyBatis configuration file, which is used to customize the conversion between database and Java types.

There may be a type mismatch between database and Java types, such as mapping a numeric type in the database to an enumeration type in Java, or dealing with datetime conversions, etc.

typeHandlers allow you to write custom type handlers to ensure correct data conversion between the database and Java.

3.1 , default type processor

The following table describes some default type handlers:

type processor

The corresponding Java type

Corresponding JDBC type

BooleanTypeHandler

Boolean

database-compatible BOOLEAN

ByteTypeHandler

Byte

database compatible NUMERIC or BYTE

ShortTypeHandler

Short

Database compatible NUMERIC or SHORT INTEGER

IntegerTypeHandler

Integer

database compatible NUMERIC or INTEGER

LongTypeHandler

Long

Database compatible NUMERIC or LONG INTEGER

StringTypeHandler

String

VARCHAR, CHAR

DateTypeHandler

Date

DATE, TIMESTAMP

EnumTypeHandler

Enum

VARCHAR

ArrayTypeHandler

Array

ARRAY

MapTypeHandler

Map

MAP

ObjectTypeHandler

Object

VARIOUS

3.2 、Custom type processor

It is possible to override type handlers or create your own to handle unsupported or non-standard types.

The specific method is:

Implement org.apache.ibatis.type.TypeHandler interface, or inherit a very convenient class org.apache.ibatis.type.BaseTypeHandler , then

It can then optionally be mapped to a JDBC type.

For example, the requirement: a Date data type in Java, I want to store it in the database as a number of milliseconds from 1970 to the present, and convert it into a java Date when it is taken out, that is, the difference between the java Date and the varchar millisecond value of the database switch between .

Development steps:

① Define the conversion class inheritance class BaseTypeHandler<T>

② Override 4 unimplemented methods:

Among them , setNonNullParameter is the callback method for java program to set data to the database, and getNullableResult is the method for converting the string type of mysql to the Type type of java during query

③ Register in the MyBatis core configuration file

④ Test whether the conversion is correct

The following is the code implementation:

Write the conversion class, inherit BaseTypeHandler<T>, and rewrite the method:

package com.xzl.handle;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * @author 逐梦苍穹
 * @date 2023/8/24 23:30
 * setNonNullParameter为java程序设置数据到数据库的回调方法
 * getNullableResult为查询时 mysql的字符串类型转换成 java的Type类型的方法
 * i 是一个整数,表示要设置的参数在 SQL 语句中的位置。
 * s 表示数据库列名
 */
public class DateTypeHandle extends BaseTypeHandler<Date> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
        // 在预处理语句中设置非空参数
        // 将 Date 类型的数据转换为 long 类型的时间戳,并以字符串形式设置到 PreparedStatement 中
        preparedStatement.setString(i, date.getTime() + "");
    }

    @Override
    public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
        // 从结果集中获取可空结果(根据列名)
        // 将结果集中的 long 类型的时间戳转换为 Date 类型并返回
        return new Date(resultSet.getLong(s));
    }

    @Override
    public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
        // 从结果集中获取可空结果(根据列索引)
        // 将结果集中的 long 类型的时间戳转换为 Date 类型并返回
        return new Date(resultSet.getLong(i));
    }

    @Override
    public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        // 从存储过程的调用结果中获取可空结果
        // 直接获取存储过程的 Date 类型数据并返回
        return callableStatement.getDate(i);
    }
}

Configure mybatis-config.xml

In this step of configuration, pay attention to the position order of this label relative to other labels. If the relative position of the label is wrong, it will appear:

③The database form and entity class should be added:

Test results:

The first is to test the timestamp stored in the database:

The result is as follows:

Then the test takes the time millisecond value in the database and converts it into a normal date class object:

The result is as follows:

4plugins

MyBatis can use third-party plug-ins to extend its functions. The paging assistant PageHelper encapsulates the complex operations of paging, and can obtain relevant data of paging in a simple way.

Development steps:

Import the coordinates of the general PageHelper

<!-- 分页助手 -->
<dependency>
  <groupId>com.github.pagehelper</groupId>
  <artifactId>pagehelper</artifactId>
  <version>3.7.5</version>
</dependency>
<!-- sql解析 -->
<dependency>
  <groupId>com.github.jsqlparser</groupId>
  <artifactId>jsqlparser</artifactId>
  <version>0.9.1</version>
</dependency>

Configure the PageHelper plug-in in the mybatis core configuration file

③Test paging data acquisition

Key code: PageHelper.startPage(1,3); indicates that it is currently on the first page and displays three pieces of data   

as follows:

Get other parameters related to pagination:

The test code is as follows:

Guess you like

Origin blog.csdn.net/qq_60735796/article/details/132487094
Recommended