在編寫sql語句時會碰到數據庫字段與我們實體類對象中屬性名不一致,導致無法給實體類屬性賦值。
數據庫:
實體類:
有以下三種方式解決:
- 方式一:在編寫SQL語句時給字段起別名與屬性名一一對應
- 方式二: 需要字段和屬性命名符合規則,我們可以在 mybatis-config.xml配置文件中設置。
字段名符合數據庫的規則(使用_命名),實體類中的屬性名符合Java的規則(使用駝峰命名法)
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
- 方式三:使用ResultMap設置自定義映射
resultMap屬性:- id:表示自定義映射的唯一標識,不能重復
- type:查詢的數據要映射的實體類的類型
- 子標簽:
- id:設置主鍵的映射關系
- result:設置普通字段的映射關系
- 子標簽屬性:
- property:設置映射關系中實體類中的屬性名
- column:設置映射關系中表中的字段名
<!-- Mapper接口全路徑 -->
<mapper namespace="com.snow.mapper.EmployeeMapper">
<!--方式三:使用ResultMap設置自定義映射-->
<resultMap id="empResultMap" type="employee">
<id property="empId" column="emp_id"></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>
</mapper>