MyBatis: getting started

Posted by whansen02 on Sat, 05 Feb 2022 14:14:09 +0100

Introduction to MyBatis

MyBatis is an open source, lightweight data persistence framework and an alternative to JDBC and Hibernate. MyBatis encapsulates JDBC internally, which simplifies the complicated process of loading drivers, creating connections, creating statements and so on. Developers only need to pay attention to the SQL statement itself.

  • Persistence layer: it can store business data to disk and has long-term storage capacity. As long as the disk is not damaged, the system can still read these data when it is restarted in case of power failure or other circumstances.
  • Advantages: huge disk space can be used to store a considerable amount of data, and it is very cheap
  • Disadvantages: slow (relative to memory)

Why use MyBatis

In our traditional JDBC, in addition to providing our own SQL, we must also operate Connection, station and ResultSet. Moreover, in order to access the data of different tables and fields, we need a lot of similar templated code, which is cumbersome and boring.

After using MyBatis, we only need to provide SQL statements. The rest, such as establishing connection, operating station, ResultSet and handling JDBC related exceptions, can be handed over to MyBatis. Therefore, we can focus on SQL statements and add, delete, modify and query these operations.

And MyBatis supports using simple XML or annotations to configure and map native information, and mapping interfaces and Java POJOs(Plain Old Java Objects) into records in the database.

Build MyBatis environment

Before actual development, we must build an appropriate environment for MyBatis. The following describes the download and directory structure of MyBatis.

MyBatis Download

On the official website of MyBatis http://mybatis.org , you can download to the latest version of MyBatis. The version used in this tutorial is MyBatis 3.5.5.

If you can't open the website or the download progress is slow, you can https://github.com/mybatis/mybatis-3/releases Download website.

Official documents are also available: Poke here , although I feel it's written in general, it still has some reference value... Alas, don't read it as a tutorial, read it as a dictionary!

After downloading and decompressing the package of MyBatis, you can get the following file directory:

MyBatis-3.5.9 Jar package is the project package of MyBatis. The [lib] folder is the third-party package that MyBatis project needs to rely on. pdf file is the description of its English version. You can stamp the link above without English.

Then, when using the MyBatis framework, its core package and dependent package need to be introduced into the application. If it is a Web application, just copy the core package and dependent package to the / WEB-INF/lib directory.

If you use Maven, POM The contents of the XML file are as follows (modify the corresponding contents according to your own version).

<dependencies>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>

</dependencies>

The first MyBatis program

Before creating the MyBatis project, first create t_user data table, SQL statement is as follows.

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

The steps to create the MyBatis program are:

  1. Configure MyBatis environment
  2. Write MyBatis core configuration file
  3. Create entity class
  4. Create DAO interface
  5. Create SQL mapping file
  6. Write test class

The following describes how to use IDEA to create a simple MyBatis program.

  1. Create a Web application and deploy a jar package (it is recommended to import Maven. The method of creating a Web project using Maven is as follows: Click Here)

    Create the Web project MyBatis quick in the IDEA, and copy the downloaded core jar package of MyBatis, the dependent jar package and the driver jar package of MySQL database to the / WEB-INF/lib directory.

  2. Create log file

    MyBatis uses log4j to output log information by default. If developers need to view the SQL statements output from the console, they can configure their log files under the classpath path path. Create log4j. In the src directory of MyBatis quick Properties file, the contents of which are as follows:

    ### 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
    
    

    Global log configuration, MyBatis log configuration and console output are configured in the log file, where MyBatis log configuration is used to The logging level of all classes under the riotian package is set to DEBUG. The content of the configuration file does not need to be handwritten by the developer. It can be downloaded from Logging section in MyBatis user manual Copy and then make simple modifications.

  3. Create persistent class

    Create a file named com. In the src directory riotian. The package of domain n, in which the persistence class User is created. Note that the attributes declared in the class are consistent with the fields in the data table User.

    package com.riotian.domain;
    
    public class User {
    
        private int id;
        private String username;
        private String password;
    
        /* get and set */
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", username='" + username + '\'' +
                    ", password='" + password + '\'' +
                    '}';
        }
    }
    
    
  4. create mapping file

    Create the [com/riotian/mapper] package in the resources directory, and create the mapping file usermapper xml

    UserMapper. The contents of the XML file are as follows:

    <?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="userMapper">
    
        <!--Delete operation-->
        <delete id="delete" parameterType="int">
            delete from user where id=#{abc}
        </delete>
    
        <!--Modify operation-->
        <update id="update" parameterType="com.riotian.domain.User">
            update user set username=#{username},password=#{password} where id=#{id}
        </update>
    
        <!--Insert operation-->
        <insert id="save" parameterType="com.riotian.domain.User">
            insert into user values(#{id},#{username},#{password})
        </insert>
    
        <!--Query operation-->
        <select id="findAll" resultType="user">
            select * from user
        </select>
    
        <!--according to id Make a query-->
        <select id="findById" resultType="user" parameterType="int">
            select * from user where id=#{id}
        </select>
    
    </mapper>
    

    In the above code, the element is the root element of the configuration file, which contains the namespace attribute. The attribute value is usually set to "package name + SQL mapping file name", which is used to specify a unique namespace.

    The information in the sub elements < Select >, < Insert > is used to perform queries and add operations. In the defined SQL statement, "#{}" represents a placeholder, equivalent to "?", "#{name}" indicates that the name of the parameter to be received by the placeholder is name.

  5. create profile

    MyBatis core configuration file is mainly used to configure various features required by database connection and MyBatis runtime, including properties that set and affect MyBatis behavior.

    Create the core configuration file MyBatis config. In the src directory XML, in which the database environment and the location of the mapping file are configured. The specific contents are as follows:

    <?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>
    
        <!--adopt properties Label load external properties file-->
        <properties resource="jdbc.properties"></properties>
    
        <!--Custom alias-->
        <typeAliases>
            <typeAlias type="com.riotian.domain.User" alias="user"></typeAlias>
        </typeAliases>
    
        <!--Data source environment-->
        <environments default="developement">
            <environment id="developement">
                <transactionManager type="JDBC"></transactionManager>
                <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>
        
    
        <!--Load mapping file-->
        <mappers>
            <mapper resource="com/riotian/mapper/UserMapper.xml"></mapper>
        </mappers>
    
    
    </configuration>
    

    The above mapping files and configuration files do not need to be written by the reader completely manually. They can be copied from the MyBatis user manual and then modified simply.

    In order to facilitate the management of configuration files required for future framework integration, you can create a new resource directory of Source Folder type under the project, and add the core configuration file of MyBatis under this directory. The default file name is "configuration.xml". However, it should be noted that in order to better distinguish various configuration files during framework integration, we generally name this file "mybatis-config.xml", which is used to configure database connection information and MyBatis parameters.

  6. Create test class

    Create a package named test under the test directory, and create the MyBatisTest test class in the package. In the test class, first use the input stream to read the configuration file, and then build the SqlSessionFactory object according to the configuration information.

    Next, create a SqlSession object through the SqlSessionFactory object, and use the method of the SqlSession object to perform database operations. The code of MyBatisTest test class is as follows:

    package Test;
    
    import com.riotian.domain.User;
    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 org.junit.Test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    public class test {
    
        @Test
        //Query an object
        public void test5() throws IOException {
            //Get core profile
            InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
            //Get the session factory object
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //Get session reply object
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //Execution operation parameters: namespace+id
            User user = sqlSession.selectOne("userMapper.findById", 1);
            //print data
            System.out.println(user);
            //Release resources
            sqlSession.close();
        }
    
        @Test
        //Delete operation
        public void test4() throws IOException {
    
            //Get core profile
            InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
            //Get the session factory object
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //Get session reply object
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //Execution operation parameters: namespace+id
            sqlSession.delete("userMapper.delete",2);
    
            //mybatis performs the update operation and commits the transaction
            sqlSession.commit();
    
            //Release resources
            sqlSession.close();
        }
    
        @Test
        //Modify operation
        public void test3() throws IOException {
            //Impersonate user object
            User user = new User();
            user.setId(2);
            user.setUsername("lucy");
            user.setPassword("123");
    
            //Get core profile
            InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
            //Get the session factory object
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //Get session reply object
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //Execution operation parameters: namespace+id
            sqlSession.update("userMapper.update",user);
    
            //mybatis performs the update operation and commits the transaction
            sqlSession.commit();
    
            //Release resources
            sqlSession.close();
        }
    
        @Test
        //Insert operation
        public void test2() throws IOException {
    
            //Impersonate user object
            User user = new User();
            user.setUsername("xxx");
            user.setPassword("abc");
    
            //Get core profile
            InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
            //Get the session factory object
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //Get session reply object
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            //Execution operation parameters: namespace+id
            sqlSession.insert("userMapper.save",user);
    
            //mybatis performs the update operation and commits the transaction
            //sqlSession.commit();
    
            //Release resources
            sqlSession.close();
        }
    
        @Test
        //Query operation
        public void testFindId() throws IOException {
            //Get core profile
            InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
            //Get the session factory object
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //Get session reply object
            SqlSession sqlSession = sqlSessionFactory.openSession();
            // Execute operation parameter namespace + id
            List<User> userList = sqlSession.selectList("userMapper.findAll");
            // print data
            System.out.println(userList);
            // Release resources
            sqlSession.close();
        }
    
    }