目錄
解決方案:
1.起別名:
2.手動結果映射:
3.開啟駝峰命名(推薦):
我們看到查詢返回的結果中大部分字段是有值的,但是deptId,createTime,updateTime這幾個字段是沒有值的,而數據庫中是有對應的字段值的,這是為什么呢?
原因如下:
-
實體類屬性名和數據庫表查詢返回的字段名一致,mybatis會自動封裝。
-
如果實體類屬性名和數據庫表查詢返回的字段名不一致,不能自動封裝。
1.起別名:
在SQL語句中,對不一樣的列名起別名,別名和實體類屬性名一樣
?@Select("select id, username, password, name, gender, image, job, entrydate, " +"dept_id AS deptId, create_time AS createTime, update_time AS updateTime " +"from emp " +"where id=#{id}")public Emp getById(Integer id);
再次執行測試類:
![]()
2.手動結果映射:
通過 @Results及@Result 進行手動結果映射
?@Results({@Result(column = "dept_id", property = "deptId"),@Result(column = "create_time", property = "createTime"),@Result(column = "update_time", property = "updateTime")})@Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id=#{id}")public Emp getById(Integer id);
@Results源代碼:
?@Documented@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD})public @interface Results {String id() default "";?Result[] value() default {}; ?//Result類型的數組}@Result源代碼:
?@Documented@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD})@Repeatable(Results.class)public @interface Result {boolean id() default false;//表示當前列是否為主鍵(true:是主鍵)?String column() default "";//指定表中字段名?String property() default "";//指定類中屬性名?Class<?> javaType() default void.class;?JdbcType jdbcType() default JdbcType.UNDEFINED;?Class<? extends TypeHandler> typeHandler() default UnknownTypeHandler.class;?One one() default @One;?Many many() default @Many;}
3.開啟駝峰命名(推薦):
如果字段名與屬性名符合駝峰命名規則,mybatis會自動通過駝峰命名規則映射
駝峰命名規則: abc_xyz => abcXyz
表中字段名:abc_xyz
類中屬性名:abcXyz
?# 在application.properties中添加:mybatis.configuration.map-underscore-to-camel-case=true
要使用駝峰命名前提是 實體類的屬性 與 數據庫表中的字段名嚴格遵守駝峰命名。