“This is the 20th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

MyBatis Config XML

The MyBatis configuration file contains Settings and property information that will deeply affect MyBatis behavior. The configuration TAB contains the following configurations. The configuration sequence must comply with the listed order

  • Properties
  • Settings
  • typeAliases
  • typeHandlers
  • objectFactory
  • Plugins
  • Environments
    • Environment (environment variable)
      • transactionManager
      • A dataSource
  • DatabaseIdProvider (Database vendor Identity)
  • Mappers (mapper)

Engineering structures,

Create maven project mybatis-config-xml to import dependencies

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.7</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.16</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.18</version>
    <scope>provided</scope>
</dependency>
Copy the code

Add entity package, add Employee entity class

@Data
public class Employee {

    private Integer id;
    private String empName;
    private String email;
    private Integer gender;
}
Copy the code

Added dao package and EmployeeDao interface

public interface EmployeeDao {

    Employee getEmpById(Integer id);
    int updateEmployee(Employee employee);
    boolean deleteEmployee(Integer id);
    int insertEmployee(Employee employee);
}
Copy the code

Add the global configuration file mybatis-config.xml to the resource directory


      
<! DOCTYPEconfiguration
        PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>    
    <! -- Set the default database to point to -->
    <environments default="dev">
        <! -- Configure the environment, different environment different ID name -->
        <environment id="dev">
            <! Commit /rollback -->
            <transactionManager type="JDBC"></transactionManager>
            <! Mysql > manage database connections by pool
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test? useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mappers/employee.xml"/>
    </mappers>
</configuration>
Copy the code

Add the mappers folder to which you add employee.xml


      
<! DOCTYPEmapper
        PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.citi.dao.EmployeeDao">

    <! -- No need to write parameter type -->
    <select id="getEmpById" resultType="com.citi.entity.Employee">
        select * from t_employee where id = #{id}
    </select>

    <! Select * from MyBatis; select * from MyBatis; select * from MyBatis; select * from MyBatis;

    <update id="updateEmployee" parameterType="com.citi.entity.Employee">
        UPDATE t_employee
        SET empname = #{empName},
        gender = #{gender},
        email = #{email}
        WHERE id = #{id}
    </update>

    <delete id="deleteEmployee">
        DELETE FROM t_employee WHERE id = #{id}
    </delete>

    <insert id="insertEmployee" useGeneratedKeys="true" parameterType="com.citi.entity.Employee">
        INSERT INTO t_employee(empname,gender,email) values (#{empName},#{gender},#{email})
    </insert>
</mapper>
Copy the code

Add logging configuration in the resource directory


      
<configuration>
   <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
       <encoder>
           <pattern>[%thread] %d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
       </encoder>
   </appender>

    <! -- Log output level (priority from high to low): error: errors - System fault logs WARN: warnings - Logs with risks or improper usage Info: general messages debug:Trace: Trace information about the execution of a program -->
    <root level="debug">
        <appender-ref ref="console"/>
    </root>
</configuration>
Copy the code

Added the EmployeeDaoTest test class

public class EmployeeDaoTest {

    SqlSessionFactory sqlSessionFactory = null;
    SqlSession openSession = null;

    @Before
    public void setUp(a) throws Exception {

        // create an SqlSessionFactory from the global configuration file
        //SqlSessionFactory: is the SqlSession factory, responsible for creating the SqlSession object;
        //SqlSession: SQL session (representing a session with the database);
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        openSession = sqlSessionFactory.openSession();

    }

    @Test
    public void getEmpById(a) throws Exception{

        EmployeeDao employeeDao = openSession.getMapper(EmployeeDao.class);
        Employee employee = employeeDao.getEmpById(1);

        System.out.println(employee);
    }


    @Test
    public void updateEmployee(a) {
        EmployeeDao employeeDao = openSession.getMapper(EmployeeDao.class);
        Employee updateEmployee = new Employee();
        updateEmployee.setId(1);
        updateEmployee.setEmpName("Tony Stark");
        updateEmployee.setEmail("[email protected]");
        updateEmployee.setGender(0);
        employeeDao.updateEmployee(updateEmployee);

        Employee employee = employeeDao.getEmpById(1);
        System.out.println(employee);
    }

    @Test
    public void deleteEmployee(a) {

        EmployeeDao employeeDao = openSession.getMapper(EmployeeDao.class);
        System.out.println(employeeDao.getEmpById(6));

        boolean isDelete = employeeDao.deleteEmployee(6);
        System.out.println(isDelete);
    }

    @Test
    public void insertEmployee(a) {

        Employee employee = new Employee();
        employee.setEmpName("peter");
        employee.setGender(0);
        employee.setEmail("[email protected]");

        EmployeeDao employeeDao = openSession.getMapper(EmployeeDao.class);
        employeeDao.insertEmployee(employee);
        System.out.println(employeeDao.getEmpById(2));
    }

    @After
    public void tearDown(a) throws Exception { openSession.close(); }}Copy the code

Perform test methods to verify that the project can run successfully

Properties property – Import external files

Create db.properties in the resource directory and configure the database connection information

jdbc_driver=com.mysql.cj.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/test? useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai
jdbc_username=root
jdbc_password=root
Copy the code

Modify mybatis global configuration file, introduce Properties, and modify database connection configuration

Add the Properties TAB under the Configuration TAB

<properties resource="db.properties" />
Copy the code

The Properties tag has two properties, both of which identify where the file is introduced

  • Resource: Reference from the classpath
  • Url: refers to a resource on a disk or network path

Modify the database connection configuration under the datasource TAB, using ${} to reference the configuration information in the database configuration file

<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>
Copy the code

Execute the getEmpById test method

Be sure to put properties first, otherwise an error will be reported

Settings property – Changes the runtime behavior of MyBatis

Settings is a very important configuration in MyBatis. It changes the runtime behavior of MyBatis. MapUnderscoreToCamelCase Indicates whether automatic mapping of camel name is enabled, that is, mapping database field A_COLUMN to entity class attribute name aColumn(database fields are case-insensitive, but are marked with underscores or not). The default value is false

Add a field create_time to the T_EMPLOYEE table and assign it to the current time. Add a property createTime to the Employee entity class

@Data
public class Employee {

    private Integer id;
    private String empName;
    private String email;
    private Integer gender;
    private Date createTime;
}
Copy the code

Execute the test getEmpById() test method

SQL > select * from database where createTime is null; Mybatis (mybatis, Mybatis, Mybatis, Mybatis, Mybatis, MyBatis, MyBatis, MyBatis, MyBatis, MyBatis

<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
Copy the code
  • Name: indicates the Key of the configuration item
  • Value: indicates the value of the configuration item

There are many keys that can be configured. Click here to view the details

Run the test again

The value of createTime was successfully obtained

TypeAliases property – Aliases the type

A type alias sets an abbreviated name for a Java type. It is only used for MyBatis global XML configuration and is intended to reduce redundant fully qualified class name writing

<typeAliases>
  <typeAlias alias="Employee" type="com.citi.entity.Employee"/>
</typeAliases>
Copy the code

Alias specifies an alias. If not, the default is the class name

When a large number of classes need to be aliased, you can batch alias through the package attribute

<typeAliases>
    <package name="com.citi.entity"/>
</typeAliases>
Copy the code

If you need a non-default Alias for a class in batches, you can add an annotation to the entity class @alias to modify the Alias tag in the employee.xml mapping file. Change the returned content resultType from com.citi.entity.Employee to Employee, which can be identified after defining the category name

<select id="getEmpById" resultType="Employee">
    select * from t_employee where id = #{id}
</select>
Copy the code

Run the test again

A full class name is recommended for quick location

TypeHandlers attribute – typeHandlers

When MyBatis sets a parameter in a PreparedStatement or fetches a value from a result set, it uses a type handler to convert the obtained value to a Java type in an appropriate manner.

<typeHandlers>
    <! -- Configure custom type handlers -->
    <typeHandler handler="Custom type processor" />
</typeHandlers>
Copy the code

MyBatis already defines most of the type handlers, so you may need to customize the type handlers when you encounter enumerated types. This configuration is rarely used

objectFactory

MyBatis will use objectFactory to encapsulate the queried data into objects by reflection, which is rarely used

The plugins properties

MyBatis allows you to intercept calls at some point during the execution of a mapping statement. By default, MyBatis allows you to intercept method calls using plug-ins:

  • Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  • ParameterHandler (getParameterObject, setParameters)
  • ResultSetHandler (handleResultSets, handleOutputParameters)
  • StatementHandler (prepare, parameterize, batch, update, query)

Plug-ins can intervene in the execution of any of the four methods on these objects through a dynamic proxy mechanism

Environment property – Supports switching between multiple environments

MyBatis uses the Environments TAB to configure multiple environments, such as development, testing, and production environments. You can use the default environment attribute to specify the default environment or switch environments

Each environment refers to an environment, and the ID attribute is a unique identifier of the environment

Spring transaction control will be used for transaction control, and database connection tools such as Druid and C3P0 will be used for data metadata configuration, rather than native database drivers

DatabaseProvider – Database migration

MyBatis can execute different statements based on different database vendors. This multi-vendor support is based on the databaseId attribute in the mapping statement. MyBatis loads statements with the databaseId attribute matching the current database and all statements without the databaseId attribute

<databaseIdProvider type="DB_VENDOR">
    <property name="MySQL" value="mysql"></property>
    <property name="Oracle" value="orcl"></property>
</databaseIdProvider>
Copy the code

Different SQL statements can be added to the SQL mapping file for different databases

<select id="getEmpById" resultType="Employee" databaseId="orcl">
    select * from t_employee where id = #{id}
</select>
Copy the code

Use frequency is low

Mappers – Batch registration

We need to tell MyBatis where to find these statements. Java doesn’t provide a great solution for automatically finding resources, so it’s best to just tell MyBatis where to find the mapping file. You can use resource references relative to the classpath, or fully qualified resource locators (including urls of the form file:///), or class names and package names, etc

<! -- Use a resource reference relative to the classpath -->
<mappers>
    <mapper resource="mappers/employee.xml"/>
</mappers>
Copy the code
<! -- Use fully qualified resource locator (URL) -->
<mappers>
  <mapper url="file:///var/mappers/employee.xml"/>
</mappers>
Copy the code
<! Use the mapper interface to implement the fully qualified class name of the class, ensuring that the XML file and the interface name are the same and in the same directory.
<mappers>
  <mapper class="com.citi.dao.EmployeeDao"/>
</mappers>
Copy the code
<! Register all mapper interface implementations in the package as mapper. Make sure that the XML file and interface name are the same and in the same directory.
<mappers>
  <package name="com.citi.dao"/>
</mappers>
Copy the code