2023-01-10
一、MyBatis自動映射與自定義映射
1、自動映射:
在映射檔案中使用的是“resultType”,指的是自動將資料庫中表的欄位與類中的屬性進行關聯映射,
2、自定義映射:
(1)在映射檔案中使用的是“resultMap”,一般是自動映射解決不了的問題,就使用自定義映射,
有“多表連接查詢,需要回傳多張表的結果集”、以及“單表查詢時,不支持駝峰式自動映射(這時一般使用別名)”
例如:在映射檔案中的實體代碼,之后在<select>中設定為“resultMap”
<resultMap id="empAndDeptResultMap" type="employee"> <!-- 定義主鍵--> <id column="id" property="id"></id> <!-- 定義非主鍵,column里面放置資料庫中的欄位,property中放置類中的屬性--> <result column="last_name" property="lastName"></result> <result column="email" property="email"></result> <result column="salary" property="salary"></result> <result column="dept_id" property="dept.deptId"></result> <result column="dept_name" property="dept.deptName"></result> </resultMap>
(2)association
<resultMap id="selectEmplAndDeptByIdAssociation" type="employee"> <!-- 定義主鍵--> <id column="id" property="id"></id> <!-- 定義非主鍵,column里面放置資料庫中的欄位,property中放置類中的屬性--> <result column="last_name" property="lastName"></result> <result column="email" property="email"></result> <result column="salary" property="salary"></result> <association property="dept" javaType="com.hh.mybatis.pojo.Dept"> <result column="dept_id" property="deptId"></result> <result column="dept_name" property="deptName"></result> </association> </resultMap>
(3)分步查詢
使用多表連接查詢,改為“分步單表查詢”,從而提高程式運行效率
3、注意:自動映射(resultType)與自定義映射(resultMap)只能同時使用一個,
二、Mybatis延遲加載
即需要時加載,不需要時暫時不加載
好處是:能提升程式運行效率
延遲加載在“mybatis-config.xml”中<setting>的設定
<settings> <setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 延遲加載--> <setting name="lazyLoadingEnabled" value="true"/> <!-- 延遲加載的屬性--> <setting name="aggressiveLazyLoading" value="false"/> </settings>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/541716.html
標籤:其他
