The result map in mybatis resultMap

Reference scene

  • When the attribute name of the entity class is different from the field name in the database, result can be used for mapping
  • In the multi-table query, you can establish a mapping to simplify database operations
  • In addition: to solve the problem of mismatch between attribute names and field names, you can also use as to alias in sql statements (more cumbersome)

The attribute name and the field name do not match (usually it is easy to ignore when looking up the table)

MyBatis will automatically create a ResultMap behind the scenes, and then map it to the properties of the JavaBean based on the property name. If the column name and attribute name cannot match, you can set the column alias
Insert picture description here
Insert picture description here
mapper mapping statement in the SELECT statement

<select id="getUsers" resultType="com.LinXiaoDe.pojo.User">
    select * from mybatis_db.user_t
</select>

In this case, there is a mismatch, pwd and password do not match, the result is empty
Insert picture description here

Solution 1: Use as mapping for sql statement


<select id="getUsers" resultType="com.LinXiaoDe.pojo.User">
    select * from mybatis_db.user_t
</select>

------------->

<select id="getUsers" resultType="com.LinXiaoDe.pojo.User">
    select id,userName,password as pwd from mybatis_db.user_t
</select>

Solution 2: resultMap mapping

The resultMap element is the most important and powerful element in MyBatis. It can free you from 90% of the JDBC ResultSets data extraction code, and in some cases allows you to perform some operations that JDBC does not support. The design idea of ​​ResultMap is to achieve zero configuration for simple statements, and for more complex statements, only the relationship between the statements needs to be described.

  • In the future, the naming of the database is generally underlined
 <resultMap id="getUserResultMap" type="com.LinXiaoDe.pojo.User">
     <id property="id" column="id"/>
     <id property="userName" column="userName"/>
     <id property="pwd" column="password"/>
 </resultMap>
 <select id="getUsers" resultMap="getUserResultMap">
     select id,userName,password from mybatis_db.user_t
 </select>

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44307065/article/details/108033884