Solution to the problem that MyBatis field names and attribute names are different

1. Give the field an alias and keep it the same as the attribute name.

    <! --List<Emp> getAllEmp( ); -->
    <select id="getAllEmp" resultType="Emp">
        select eid , emp_name empName , age , sex, email from t_emp
    </ select>

For example, the above SQL statement aliases emp_name to the attribute name of the entity class corresponding to empName.

2. Set the global configuration and automatically map _ to camel case (turn on camel case matching)

After turning on camel case matching, _ will be automatically mapped to camel case. For example, emp_name will be mapped to empName. 


In Spring Boot, when using MyBatis, you can application.ymlturn on camel case matching by setting the following parameters in the file:

mybatis:
  configuration:
    map-underscore-to-camel-case: true

 After this setting, MyBatis will convert the underscore-separated field names in the database into camelCase naming in Java. For example, if a field in the database is named user_name, it will be mapped to in Java userName.

 3. Solve the mapping relationship between field names and attribute names through resultMap

resultMap: Set custom mapping

  • Attributes:
    • id: represents the unique identifier of the custom mapping, which cannot be repeated.
    • type: The type of entity class to be mapped to the queried data
  • Sub tags:
    • id: Set the mapping relationship of the primary key
    • result: Set the mapping relationship of common fields
    • Subtag attributes:
      • property: Set the attribute name in the entity class in the mapping relationship
      • column: Set the field name in the database table in the mapping relationship
      • association: javaBean encapsulates an entity (many-to-one);
      • Collection: Used for javaBean to encapsulate a collection (one-to-many).
  • If the field name is inconsistent with the attribute name in the entity class, you can set a custom mapping through resultMap. Even the attributes with the same field name and attribute name must be mapped, that is, all attributes must be listed.
<resultMap id="empResultMap" type="Emp">
	<id property="eid" column="eid"></id>
	<result property="empName" column="emp_name"></result>
	<result property="age" column="age"></result>
	<result property="sex" column="sex"></result>
	<result property="email" column="email"></result>
</resultMap>
<!--List<Emp> getAllEmp();-->
<select id="getAllEmp" resultMap="empResultMap">
	select * from t_emp
</select>

Guess you like

Origin blog.csdn.net/weixin_55772633/article/details/132881383