Use the MyBatis framework to operate the Mysql database

Posted by joshmpratt on Sun, 16 Jan 2022 15:50:09 +0100

Brief description of MyBatis (reference from: What is mybatis_ Baidu knows (baidu.com))

  1. MyBatis was originally an open source project ibatis of apache. In 2010, the project was migrated from apache software foundation to google code and renamed MyBatis. Moved to Github in November 2013.

  2. MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures and advanced mapping. MyBatis eliminates almost all the manual setting of JDBC code and parameters and the retrieval of result sets. MyBatis uses simple XML or annotations for configuration and original mapping, and maps the interface and Java POJOs (Plain Old Java Objects) into records in the database.

  3. Each MyBatis application mainly uses SqlSessionFactory instances. A SqlSessionFactory instance can be obtained through SqlSessionFactoryBuilder. SqlSessionFactoryBuilder can be obtained from an xml configuration file or an instance of a predefined configuration class.

Operation steps

  1. Create a maven project using IDEA (for a brief introduction to Maven project, refer to: maven (I) what the hell is maven ~ - Lao Wang with dreams - blog Garden (cnblogs.com) )The maven project is shown in the figure. You can directly next
  2. Add related dependencies. Configure POM XML file:
    <?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>
        <!--Define local warehouse attributes to ensure uniqueness-->
        <groupId>com.southwind</groupId>
        <artifactId>MyBatisTest</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <maven.compiler.source>11</maven.compiler.source>
            <maven.compiler.target>11</maven.compiler.target>
        </properties>
        <!--Import dependency-->
        <dependencies>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.5</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.11</version>
            </dependency>
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.6</version>
                <scope>provided</scope>
            </dependency>
    
        </dependencies>
        <!-- build This is where he can access java Under the directory.xml Document from: https://blog.csdn.net/taiyangdao/article/details/52374125 -->
        <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                    </includes>
                </resource>
    
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>*.xml</include>
                        <include>*.properties</include>
                    </includes>
                </resource>
            </resources>
        </build>
    
    </project>
  3. Create a new table in the database and create the table code: (mysql is a relational database)
    CREATE DATABASE mybatis CHARACTER SET utf8 COLLATE utf8_general_ci;
    USE mybatis;
    CREATE TABLE `t_account`(
    	id INT PRIMARY KEY AUTO_INCREMENT,
    	username VARCHAR(11),
    	`password` VARCHAR(11),
    	age INT
    )ENGINE=INNODB DEFAULT CHARSET=utf8;

    (learn about mysql: [crazy God talking about Java] the latest tutorial of MySQL is easy to understand_ Beep beep beep_ bilibili)

  4. Create a new entity class Account. Package structure:Specific reference code: (it is better that the order of member variables corresponds to that when creating tables in the database)

    package com.southwind.entity;
    
    import lombok.AllArgsConstructor;
    import lombok.NoArgsConstructor;
    import lombok.Data;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Account {
        private long id;
        private String username;
        private String password;
        private int age;
    }
    
  5. Create the configuration file config. For MaBatis XML to build the environment, and the file name can be customized. Package structure:Specific code
    <?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>
    
        <!-- to configure mybatis Operating environment-->
        <environments default="development">
            <environment id="development">
                <!-- to configure JDBC transaction management -->
                <transactionManager type="JDBC"></transactionManager>
                <!-- pooled to configure JDBC Data source connection pool  -->
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver" ></property>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"></property>
                    <property name="username" value="root"></property>
                    <property name="password" value="123456"></property>
                </dataSource>
            </environment>
        </environments>
    
        <!-- register AccountMapper.xml,Write later Mapper Added after document -->
        <mappers>
            <mapper resource="com/southwind/mapper/AccountMapper.xml"></mapper>
        </mappers>
    
    </configuration>
  6. Write mapper XML file. (use the native interface. The MyBatis framework requires developers to customize SQL statements and write them in Mapper.xml. In actual development, a corresponding Mapper.xml will be created for each entity class to define the SQL for managing the object data). Package structureSpecific code
    <?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.southwind.mapper.AccountMapper">
        <insert id="save" parameterType="com.southwind.entity.Account">
            insert into t_account(username,password,age) values(#{username},#{password},#{age})
        </insert>
    </mapper>

    The namespace is usually set in the form of package + file name where the file is located; The insert tag indicates that the add operation is performed; The select tag indicates to execute the query operation; The upadate tag indicates that the update operation is performed; The delete tag indicates that the deletion operation is performed; id is the parameter required when actually calling the MyBatis method; parameterType is the data type of the parameter when the method is called

  7. Call the MaBatis native interface to perform the add operation (create the test class, the following is the package structure)code:
    package com.southwind.test;
    
    import com.southwind.entity.Account;
    import org.apache.ibatis.session.*;
    import java.io.*;
    
    public class Test {
        public static void main(String []args){
            //Load mybatis configuration file
            InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            SqlSessionFactory  sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
            SqlSession sqlSession  = sqlSessionFactory.openSession();
            String statement = "com.southwind.mapper.AccountMapper.save";
            Account account = new Account(1l,"Zhang San","1231231",22);
            sqlSession.insert(statement,account);
            sqlSession.commit();
        }
    }
    
  8. After the test class is written, you can see that the database is added successfully, as shown in the figure

Problems encountered and some solutions

  1. A large area of red flags appears, but the related dependencies are displayed and imported, which may not be loaded and downloaded. The related dependencies can be downloaded automatically by refreshing the dependencies
  2. There is no red report, but there is a problem in operation. Please check whether the code in "" is wrong, because there are errors in it and there will be no prompt. At the same time, you can also quickly locate through prompts

Learning MyBatis resources( [introduction to minimalism] learn MyBatis in 4 hours_ Beep beep beep_ bilibili)

Topics: Java Database MySQL