1. ResultMap

Null query result: Inconsistent attribute and field name to resolve

Let’s start with the steps:

  1. The name of a field in the database

  2. Entity classes in Java

    public class User {
     
        private int id;  //id
        private String name;   / / name
        private String password;   // The password is different from the database!
        
        / / structure
        //set/get
        //toString()
    }
    Copy the code
  3. Mapper interface method

    // Query users by id
    User selectUserById(int id);
    Copy the code
  4. Mapper configuration file

    <select id="selectUserById" resultType="user">
        select * from user where id = #{id}
    </select>
    Copy the code
  • MyBatis will search for the set method of the corresponding column name in the corresponding entity class according to the column name of these queries (the column name will be automatically converted to lowercase, the database is case-insensitive). Because setPwd cannot be found, So password returns NULL ** (automatic mapping) **

  • Solutions:

    1. Specify an alias for the column name that matches the property name of the Java entity class

      <select id="selectUserById" resultType="User">
          select id , name , pwd as password from user where id = #{id}
      </select>
      Copy the code
    2. Using result set mapping (recommended)

      <resultMap id="UserMap" type="User">
          <! -- id primary key -->
          <id column="id" property="id"/>
          <! Column specifies the column name of the database table, and property specifies the property name of the corresponding entity class.
          <result column="name" property="name"/>
          <result column="pwd" property="password"/>
      </resultMap>
       
      <select id="selectUserById" resultMap="UserMap">
          select id , name , pwd from user where id = #{id}
      </select>
      Copy the code

Automatic mapping:

  • The resultMap element is the most important and powerful element in MyBatis. It frees you from 90% of the JDBC ResultSets data extraction code

  • In fact, when writing mapping code for complex statements such as joins, a resultMap can replace thousands of lines of code that perform the same function

  • The idea behind ResultMap is that for simple statements you do not need to configure an explicit ResultMap at all, while for more complex statements you only need to describe their relationships

    <select id="selectUserById" resultType="map">
    select id , name , pwd
        from user
        where id = #{id}
    </select>
    Copy the code

Manual mapping:

  • The return value type is resultMap

    <select id="selectUserById" resultMap="UserMap">
        select id , name , pwd from user where id = #{id}
    </select>
    Copy the code
  • Compile resultMap to achieve manual mapping

    <resultMap id="UserMap" type="User">
        <! -- id primary key -->
        <id column="id" property="id"/>
        <! Column specifies the column name of the database table, and property specifies the property name of the corresponding entity class.
        <result column="name" property="name"/>
        <result column="pwd" property="password"/>
    </resultMap>
    Copy the code
  • However, in the database, there are one-to-many and many-to-one situations, and we will use some advanced result set mappings, such as Association and collection, later

2. Log factory

2.1 concept

Mybatis built-in log factory provides log function, specific log implementation has the following tools:

  • SLF4J
  • Apache Commons Logging
  • Log4j2
  • Log4j
  • JDK logging
  • MyBatis’ built-in log factory determines which logging implementation tool to choose. It uses whatever it finds first (in the order listed above). If none is found, logging is disabled

Standard logging implementation:

  • Specifies which logging implementation MyBatis should use. If this setting does not exist, the logging implementation is automatically discovered

    <settings>        <setting name="logImpl" value="STDOUT_LOGGING"/></settings>
    Copy the code

2.2 the Log4j

About Log4j:

  • Log4j is an open source project of Apache
  • Using Log4j, we can control the destination of log message delivery: console, text, GUI components, and so on
  • We can also control the output format of each log
  • By defining the level of each log message, we can more carefully control the log generation process. The most interesting thing is that these can be configured flexibly through a configuration file without the need to modify the application code

Use steps:

  1. Guide package

    <dependency>    <groupId>log4j</groupId>    <artifactId>log4j</artifactId>    <version>1.2.17</version></dependency>
    Copy the code
  2. Preparation of configuration files

    Output DEBUG logs to the console and file destinations Log4j.appender. console = log4j.appender.console = log4j.appender.console = log4j.appender.console = org.apache.log4j.ConsoleAppenderlog4j.appender.console.Target = System.outlog4j.appender.console.Threshold=DEBUGlog4j.appender.console.layout = Org, apache log4j. PatternLayoutlog4j. Appender. Console. Layout. The ConversionPattern = % [c] - % m % n # file output associated Settings log4j. Appender. The file = org.apache.log4j.RollingFileAppenderlog4j.appender.file.File=./log/kuang.loglog4j.appender.file.MaxFileSize=10mblog4j.ap pender.file.Threshold=DEBUGlog4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.Conversio nPattern=[%p][%d{yy-MM-dd}][%c]%m%n # log4j.logger.org.mybatis=DEBUGlog4j.logger.java.sql=DEBUGlog4j.logger.java.sql.Statement=DEBUGlog4j.logger.java.s log output level ql.ResultSet=DEBUGlog4j.logger.java.sql.PreparedStatement=DEBUG
    Copy the code
  3. Setting Sets the implementation of logging

    <settings>    <setting name="logImpl" value="LOG4J"/></settings>
    Copy the code
  4. Use Log4j in the program for output

    / / note that guide package: org, apache log4j. Loggerstatic Logger Logger = Logger. GetLogger (MyTest. Class); @testPublic void selectUser() {logger.info("info: enter selectUser method "); Logger. debug("debug: enter selectUser method "); Logger. error("error: enter selectUser method "); SqlSession session = MybatisUtils.getSession(); UserMapper mapper = session.getMapper(UserMapper.class); List
            
              users = mapper.selectUser(); for (User user: users){ System.out.println(user); } session.close(); }
            
    Copy the code
  5. test

3. The paging

3.1 limit implements paging

Why use paging?

  • When learning the persistence layer framework such as Mybatis, we will often add, delete, change and check the data, and the most used is to query the database. When we query a large number of data, we often use paging to query, that is, to process a small amount of data at a time, so that the pressure on the database is under control

Paging with Limit:

# grammarSELECT * FROM tableLIMIT stratIndex, pageSizeSELECT * FROM table LIMIT 5.10; //Retrieve record row6- 15To retrieve all rows from an offset to the end of the recordset, specify the second parameter- 1:SELECT * FROM table LIMIT 95.- 1; //Retrieve record row96-Last. # If only one argument is given, it indicates the maximum number of rows to return:SELECT * FROM table LIMIT 5; //Retrieve the former5In other words, LIMIT n is equivalent to LIMIT0, n.Copy the code

Steps:

  1. Modify the Mapper configuration file

    <select id="selectUser" parameterType="map" resultType="user">    select * from user limit #{startIndex}, #{pageSize}</select>
    Copy the code
  2. Example To modify the Mapper interface, set the parameter to map

    List
            
              selectUser(Map
             
               Map);
             ,integer>
            
    Copy the code
  3. Test (inference: Starting position = (current page -1) * page size)

    // page query, two parameters startIndex, pageSize@Testpublic void testSelectUser() {SqlSession session = myBatisutils.getSession (); UserMapper mapper = session.getMapper(UserMapper.class); int currentPage = 1; Int pageSize = 2; // Display several maps per page 
            
              Map = new HashMap
             
              (); map.put("startIndex",(currentPage-1)*pageSize); map.put("pageSize",pageSize); List
              
                users = mapper.selectUser(map); for (User user: users){ System.out.println(user); } session.close(); }
              
             ,integer>
            ,integer>
    Copy the code

3.2 RowBounds paging

In addition to using Limit to paging at the ==SQL level, we can also use RowBounds to paging at the Java code level.

  1. Add Mapper interface methods

    List
            
              getUserByRowBounds();
            
    Copy the code
  2. Boundary Mapper configuration file

    <select id="getUserByRowBounds" resultType="user">    select * from user</select>
    Copy the code
  3. Testing (using the RowBonds class)

    @Testpublic void testUserByRowBounds(a) {    SqlSession session = MybatisUtils.getSession();     Int currentPage = 2; Int pageSize = 2; RowBounds rowBounds = new RowBounds((currentPage - 1) * pageSize, pageSize); // Pass rowBounds through the session. XXX method, (this way is not recommended now) List < User > users = session. The selectList (" top. Linzelaing. Mapper. UserMapper. GetUserByRowBounds ", null, rowBounds); for (User user: users){ System.out.println(user); } session.close(); }
    Copy the code
    • In fact, this method is to query all the data first, and then filter, which will lead to increased pressure on the server, not recommended

3.3 PageHelper implements paging

  • Understanding can
  • Click to view the official website