Initial MyBatis, Quick Start and Profile Mapping File Explanation (Construction Idea Explanation, Graphics and Text Teaching, Full Practice)

Keywords: Mybatis log4j JDBC Attribute

1. Introduction

  • Persistence Layer Framework, java Writing
  • It encapsulates jdbc internally, so that developers only need to pay attention to sql statement s themselves, and do not need to spend energy to deal with the complicated process of loading driver, creating connection, creating state and so on.
  • Using ORM idea, ORM: Object Relational Mapping Object Relational Mapping is mapping database tables and entity classes, and operating entity classes can achieve the operation of database tables.

2. Environmental Construction

  1. Create the parent project mybatistest, delete unwanted packages (src), add coordinates, and modify the pom file
<dependencies>
        <!--mybatis frame-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <!--Database Connection (Choose the database that suits you)-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>
        <!--Log information (in order to be able to see more detailed information, you can only get results if you don't add it)-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <!--unit testing-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>
  1. Preparing database resources
create database mybatistest;
use mybatistest;
drop table if exists `user`;
create table `user`(
	`id` int(10) primary key auto_increment,
	`name` varchar(20),
	`age` int(3)
);
insert into `user`(`name`,`age`) values('Xiao Ming',22);
insert into `user`(`name`,`age`) values('Xiaohong',25);

3. day1 - Introduction

We have completed the construction of our father's project. Next we will officially begin our first day of study.

3.1 Submodule Preparations

  1. Under the parent project, create the sub-project day1, because we imported coordinates into the parent project, and all the sub-projects do not need to import.
  2. Import the log configuration file log4j.properties. This file can be placed under the resources folder without special relationship. It can be created and pasted directly.
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
  1. Create the entity class com.lois.domain.User. In the introduction, we said that mybatis is ORM idea, so we need to create the entity class mapping database table. Note: Produce set and get and toString methods by ourselves.
public class User implements Serializable {
    private Integer id;
    private String name;
    private Integer age;
 }

3.2 Quick Start

In the Quick Start phase, let's write the simplest example of querying all users

  1. Create the com.lois.dao.UserDao interface and write the interface method
public interface UserDao {
    /**
     * Query all users
     * @return
     */
    public List<User> findAll();
}
  1. Create the mapping file com/lois/dao/UserDao.xml, which is located under the resources folder. Note: The path must be consistent with the first Dao
<?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">
<!-- namespace Specify interface (full class name)-->
<mapper namespace="com.lois.dao.UserDao">
    <select id="findAll" resultType="com.lois.domain.User">
        select * from user;
    </select>
</mapper>
  1. Create the SqlMapConfig.xml configuration file under the resources folder to specify the factory configuration. mybatis needs to get information about the database and the location of the mapping file, and modify it according to its own situation.
<?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>
    <environments default="mysql">
        <!--To configure mysql Environmental Science-->
        <environment id="mysql">
            <!--Configure transaction types-->
            <transactionManager type="JDBC"></transactionManager>
            <!--Configuring the data source (connection pool) needs to be modified by itself-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatistest?serverTimezone=UTC&amp;characterEncoding=utf-8&amp;useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="1234567"/>
            </dataSource>
        </environment>
    </environments>

    <!--Specify mapping file-->
    <mappers>
        <mapper resource="com/lois/dao/UserDao.xml"/>
    </mappers>

</configuration>
  1. Next we can start testing and create the com.lois.test.MybatisTest test test test class under the Test package.
public class MybatisTest {

    @Test
    public void test1() throws IOException {
        //1. Get factory drawings (configuration information)
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2. Recruitment of workers (founder)
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //3. Build factories for workers'drawings (builders build factory objects)
        SqlSessionFactory factory = builder.build(in);
        //4. Build a product pipeline (open automatic commit transaction)
        SqlSession session = factory.openSession(true);
        //5. Produce products according to product design drawings (dynamic agent)
        UserDao userDao = session.getMapper(UserDao.class);
        //6. Use products
        List<User> users = userDao.findAll();
        for (User user :
                users) {
            System.out.println(user);
        }
        //7. Recycling (Releasing Resources)
        session.close();
        in.close();
    }
}
  1. Run the test class and the console outputs the content.
2019-08-11 09:21:25,572 0      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
2019-08-11 09:21:25,844 272    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2019-08-11 09:21:25,844 272    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2019-08-11 09:21:25,844 272    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2019-08-11 09:21:25,844 272    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2019-08-11 09:21:25,969 397    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2019-08-11 09:21:26,454 882    [           main] DEBUG source.pooled.PooledDataSource  - Created connection 728258269.
2019-08-11 09:21:26,454 882    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2b6856dd]
2019-08-11 09:21:26,456 884    [           main] DEBUG   com.lois.dao.UserDao.findAll  - ==>  Preparing: select * from user; 
2019-08-11 09:21:26,487 915    [           main] DEBUG   com.lois.dao.UserDao.findAll  - ==> Parameters: 
2019-08-11 09:21:26,545 973    [           main] DEBUG   com.lois.dao.UserDao.findAll  - <==      Total: 2
User{id=1, name='Xiao Ming', age=22}
User{id=2, name='Xiaohong', age=25}
2019-08-11 09:21:26,548 976    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2b6856dd]
2019-08-11 09:21:26,549 977    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2b6856dd]
2019-08-11 09:21:26,549 977    [           main] DEBUG source.pooled.PooledDataSource  - Returned connection 728258269 to pool.

4. Thinking

The introduction to mybatis is actually relatively simple, with only four steps:

  1. Guide packages and create entity classes
  2. Write dao interface and mapping file
  3. Write the factory drawings configuration file (SqlMapConfig.xml)
  4. Writing test classes

So let's look at these four steps in detail.

4.1 Guide and Entity Classes

I'll stop talking about the tutorial and talk about the entity class. Mybatis is an ORM idea, so the entity class is like a table in the database. The fields in the table correspond to the attributes of the entity class. An instance of the entity class corresponds to a row of data in the database table. When we modify the instance of the entity class, we pass it to mybatis. Mybatis synchronizes the information we modify to the number. In the database table. This also implements that we modify the entity class is to modify the database table. Of course, it's important to note that the attribute type of the entity class matches the type of the field in the database. Another usage of entity class is that entity class contains another entity class. Why? In fact, this is to achieve the relationship in the database: one-to-one, one-to-many, many-to-one, many-to-many. This question will be discussed in a later chapter.

4.2 dao interface and mapping file

With the mybatis framework, we don't need to write our own persistence layer implementation classes, but we still need to write our persistence layer interface, because we want to tell mybatis what methods we need, we tell mybatis what methods we need, but what information can the interface provide? Method name, return type, parameter list. This information is not enough, and sql statements are needed, so there is a mapping file. This mapping file maps the method in the dao interface. The mapping file tells the sql statement of the method in the mybatis interface, so mybatis can help us complete the dao operation.
There's nothing to say about the dao interface, just like we didn't use a framework before, so let's talk about this mapping file.

Mapping file requirements:

  • Create location: Must be in the same package as the persistence layer interface.
  • Name: The file name must end with Dao or Map with the name of the persistent layer interface. The extension is. xml. For example, if the interface is UserDao, then the name of the mapping file should be UserDao.xml or UserMap.xml.

Mapping the label in the file:

  • mapper tag
    • namespace property: specifies the dao interface for mapping files, the full class name
  • resultMap result mapping: Used to customize the corresponding relationship when the query result does not match the entity class so that it can be encapsulated
    • id attribute: unique identifier that can be used in select Tags
    • type attribute: Specifies the full class name of the entity class
      • Subtag id tag: Used to specify primary key fields
      • Sublabel result tag: Used to specify non-primary key fields
        • Sublabel attribute column: Used to specify database column names
        • Sublabel property: Used to specify the entity class property name
  • select, update, insert, delete tags: corresponding additions, deletions and modifications
    • id attribute: specifies which method, method name, to map the dao interface
    • parameterType attributes: parameter type, base type and String can write type names directly, and others need to write full class names.
    • resultType attribute: Return type, base type and String can write the type name directly, and others need to write the full class name. Property names in entity classes must be consistent with column names in query statements, otherwise encapsulation cannot be implemented.
    • ResultMap attribute: When the query result does not match the entity class, we can use the mapping defined by resultMap above to fill in the mapping id
    • Tag content: sql statement + placeholder
      • placeholder
        • # {}: Represents a placeholder (commonly used)
          preparedStatement can set values to placeholders by {} and automatically convert java type to jdbc type. {} can effectively prevent sql injection. # {} Simple type values or entity class attribute names can be accepted. If parameterType transports a single simple type value, #{} brackets can be value or other names (with arbitrary names). If parameterType passes an entity class, #{} parentheses can be the entity class attribute name.
        • ${}: Represents spliced sql strings (not commonly used)
          ParameterType can be spliced into sql by ${} without jdbc type conversion, and ${} can receive simple type values or entity class attribute names. If parameterType transmits a single simple type value, ${} can only be value in parentheses.

4.3 SqlMapConfig.xml Configuration Content

  • configuration tag: external master tag, nothing to say

    • Property tag: used to load some configuration information
      • resource attribute: specify the name of the file that loads the information (under the resources folder). file of type properties (key=value type)
      • url attributes: use url paths to access loaded files, the file type is the same as above
      • property subtags: Just put the contents of the load file above in the tag attributes (insignificant, not commonly used)
        • name attribute: key corresponding to the file loaded above
        • Value attribute: value corresponding to the file loaded above
      • Effect: We can get the value of key in the loading file by ${key}. We usually put the information of the data source in the external loading file and get it by ${key} in the data source, so that we can modify the external loading file directly without moving the data source.

    • TypeeAliases tag: Type aliases, let's configure without writing the full class name. This setting is valid not only in the SqlMapConfig.xml file, but also in the dao mapping file.
      • TypeeAlias Subtag: Single Alias Settings
        • Alias attribute: alias
        • type property, set the full class name of the alias
      • Package tag: Set aliases in batches, scan classes under the whole package, and alias class names (capitals or lowercases can be used)
        • name attribute: the package path that needs to be scanned

  • mappers tag: configure dao mapping file location

    • mapper subtag: single mapping file location
      • resource attribute: Find the dao mapping file with respect to the class path
        • <mapper resource="com/lois/dao/UserDao.xml"/>
      • Class attribute: using mapper interface class path
        • <mapper class="com.lois.dao.UserDao"/>
        • Note: This method requires the mapper interface name to be the same as the mapper mapping file name and to be placed in the same directory.
    • Package tag: Register all mapper interfaces under the specified package
      • <package name="com.itcast.dao">
      • Note: This method requires the mapper interface name to be the same as the mapper mapping file name and to be placed in the same directory.

4.4 Writing Test Classes

In the test class, I've written seven memorable steps in the annotations. In fact, two modes are used here: the builder mode and the factory mode. We used the builder model in building factories and the factory model in production. So why do we use so many steps? Why not put it in place one step at a time? This is because we use the mybatis framework to let us implement dao. Every additional step will give mybatis more flexibility and more choices, which is very beneficial. Mybatis uses dynamic proxy in step 5 to produce the product, which enhances the Dao interface class we write and implements the method in the interface, so that we can not write the Dao class.

5 homework

If you understand the above thinking, then you should be able to write basic additions, deletions, checks and changes, please try, of course, the above thinking is a little bit more, we will continue to explain in the following chapters, do not understand it is okay.

Posted by jobs on Tue, 13 Aug 2019 03:11:23 -0700