The use of resultType and resultMap in mybatis

Both are output result types.

1、resultType

        resultType can output simple types

     <!-- 查询数据的条数 -->
    <select id="queryUserCount" resultType="int">
        SELECT count(*) FROM  user
    </select>
        Output pojo object
 
     <select id="queryUser"  resultType="com.star.entity.User">
         SELECT * FROM `user` WHERE id=#{id}
     </select>

        Note: When using resultType, make sure that the column name of the database is the same as the attribute name of the Java entity class, otherwise the output result code will receive null. I've encountered this problem several times.

2、resultMap

        

<resultMap  id="baseResultType" type="com.star.entity.user">
        <!-- property:主键在实体类中的属性名 -->
        <!-- column:主键在数据库中的列名 -->
       
        <id property="id" column="user_id" />

        <!-- 定义普通属性 -->
        <result property="name" column="user_name" />
        <result property="number" column="user_number" />
    </resultMap>

    <!-- 查询所有的用户 -->
    <select id="queryUserAll" resultMap="baseResultType">
        SELECT * FROM user
    </select>

        Note: resultMap is suitable for use when the return value is a custom entity class. It establishes a corresponding relationship between field names and attribute names. If the SQL query database field names are inconsistent with the attribute names in the entity class, their mapping relationship needs to be defined.

        Usually database fields are somewhat different from fields in entity classes. At this time, resultMap is often used for mapping relationships.

Guess you like

Origin blog.csdn.net/m0_71867302/article/details/132826218