Mybatis_resultMap

The name of the attribute in the class must be the same as the attribute name of the database, otherwise it cannot be found. However, in the development, the database attribute is named with an underscore, and the attribute in the class is in camel case, so sometimes the names are different. All with resultMap

The resultMap is used in scenarios where there is a mapping, and the Java entity class attribute name is different from the database field name.

<?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: The namespace of the mapping file, the content specification is the package name of the mapping file. This xml file name --> 
< mapper namespace = "xxx.x.mapper.PersonTestMapper" >


    <!--
        The type of resultMap is the entity class (entity data type), and the id is the unique identifier of the resultMap. The original resultType below is removed and changed to resultMap, and the value is this id.
        Except for the id column in the table, which is represented by id, the rest are represented by result, and all attributes must be written
        column represents the field name in the table, property represents the name of the property in the entity class
    -->
    <resultMap type="xxx.x.Person" id="BaseResultMap"> 
        <id column = "person_id" property = "personId" />
        <result column = "name" property = "name" />
        <result column = "gender" property = "gender" />
        <result column = "person_addr" property = "personAddr" />
        <result column = "birthday" property = "birthday" />
        
    </resultMap>
    <!-- 
        parameterType is the type of the passed parameter, the following is the integer writing
        The last parameter id of the sql statement is a variable
        resultType is the result of the query, the content is the address that needs to be output, and the properties that need to receive data need to be defined in the Person class
        #{}Use the precompiled method to generate SQL to prevent SQL injection
     -->
    <select id="selectPersonByID" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select * from person_test where id = #{id}
    </select>
    
</mapper>

But resultType is not useless, it needs to be used in the following cases, without mapping:

    <select id="selectPersonCount" resultType="java.lang.Integer" >
        select count(*) from person
    </select>

The java statement to call this is:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325141732&siteId=291194637