原文鏈接:https://blog.csdn.net/zx48822821/java/article/details/79050735
因為數據庫一般設置為表的字段不區分大小寫,所以數據庫中表的字段通常是以 _ 來進行詞組划分的,比如 user 表中字段名會有: user_id、user_name、user_pwd :
create table user( user_id int pramary key not null, user_name varchar(20) not null, user_pwd varchar(20) not null )
但是 User 的實體類一般會寫為:
public class User{ private int userId ; private String userName; private String userPwd; }
這是由於 JAVA 是區分大小寫的,可以采用駝峰標識來進行詞組划分。而在這種情況下 Mybatis 無法完成字段的自動映射。但我們又不應該直接更改數據庫及實體類。所以有解決該問題的三種方式:
1.起別名
在 SQL 語句中為字段名標記與實體類屬性相同的名稱:
<select id="selectUserById" resultType="User"> select user_id as userId , user_name as userName, user_pwd as userPwd, from user where user_id = #{userId} </select>
2.resultMap指定映射關系
<resultMap type="User" id="UserResultMap"> <id column="user_id" property="userId"/> <result column="user_name" property="userName"/> <result column="user_pwd" property="userPwd"/> </resultMap> <select id="selectUserById" resultMap="UserResultMap"> select user_id, user_name, user_pwd, from user where user_id= #{user_id} </select>
注意:
1.使用resultMap時,在select語句配置中,要有resultMap替換原來的resultType。
2.resultMap中的column要與查詢到的字段名一致,property要與實體類的屬性一致。
3.Mybatis 全局屬性 mapUnderscoreToCamelCase
在通常情況下,java中的實體類中的屬性一般是采用駝峰命名命名的,而數據庫中表的字段則用下划線區分字母。在這種情況下,Mybatis提供了一個全局屬性mapUnderscoreToCamelCase來解決兩者名字不一致的問題。
<settings> <!--其他配置... --> <setting name="mapUnderscoreToCamelCase" value="true"/> <!--其他配置... --> </settings>
注意:因為該屬性是全局屬性,所以需要配置在Mybatis的配置文件中,而不是Mapper.xml映射文件中。