如果資料庫欄位和物體類中的屬性欄位存在不一致情況,三種方式可解決,通常可自定義resultMap來映射;另外還可以通過sql陳述句的別名和開啟下劃線轉駝峰的方式來映射,
1.resultMap映射
1.resultMap:設定自定義映射
屬性:
id:表示自定義映射的唯一標識,不能重復
type:查詢的資料要映射的物體類的型別
子標簽:
id:設定主鍵的映射關系
result:設定普通欄位的映射關系
子標簽屬性:
property:設定映射關系中物體類中的屬性名
column:設定映射關系中表中的欄位名
若欄位名和物體類中的屬性名不一致,則可以通過resultMap設定自定義映射,即使欄位名和屬性名一致的屬性也要映射,也就是全部屬性都要列出來
<resultMap id="empResultMap" type="com.nmg.mybatis.pojo.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> <select id="getAllEmp" resultMap="empResultMap"> select * from t_emp; </select>
2.SQL起別名
sql陳述句中,將資料庫中的emp_name欄位用別名empName表示(empName為物體類中的屬性)
<select id="getAllEmp" resultType="com.nmg.mybatis.pojo.Emp">
select eid,emp_name empName,age,sex,email from t_emp
</select>
3.全域配置資訊mapUnderscoreToCamelCase
可以在MyBatis的核心組態檔中的setting標簽中,設定一個全域配置資訊mapUnderscoreToCamelCase,可以在查詢表中資料時,自動將_型別的欄位名轉換為駝峰,例如:欄位名emp_name,設定了mapUnderscoreToCamelCase,此時欄位名就會轉換為empName,
mybatis:
# 自動配置物體類
type-aliases-package: com.medical.medical.entity
# 自動映射mapper下的**.xml檔案
mapper-locations: mapper/*.xml
configuration:
# 全域配置資訊:自動將資料庫欄位_型別的欄位名轉換為駝峰命名:department_id --> departmentId
map-underscore-to-camel-case: true
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/508100.html
標籤:其他
上一篇:Java 中HashMap 詳解
