物體類中的變數與資料庫對應表的變數名不一致,如果sql 中沒有添加別名, 那么會找不到對應的欄位, 則會報空指標例外,如果物體類和資料庫欄位一樣則不需要加As
方法1:sql陳述句 使用 as
方法2:mybatis里面使用 resultMap
案例:
資料庫表:

類company成員變數:

當資料庫的欄位名和我們的類的成員變數名不一致,主要通過兩種方法實作映射:
1、通過sql陳述句,使用 as 起別名
原來:select * from ss_company
改后:
companyDao.xml
<select id="findAll" resultType="company">
select
id,
name ,
expiration_date as expirationDate ,
address,
license_id as licenseId ,
representative ,
phone ,
company_size as companySize ,
industry ,
remarks ,
state,
balance ,
city
from ss_company
</select>
2、通過resultMap標簽進行資料庫列與類的成員變數的映射
resultMap標簽進行資料庫與物體類的映射
- 標簽id,對應資料庫表的主鍵
- 標簽result,對應資料庫非主鍵的其他列(
把名不一樣的改即可) - 屬性column對應資料庫表的列名,屬性property對應物體類
companyDao.xml
<resultMap id="companyMap" type="company">
<id column="id" property="id"/>
<result column="expiration_date" property="expirationDate"/>
<result column="license_id" property="licenseId"/>
<result column="company_size" property="companySize"/>
</resultMap>
<select id="findAll" resultMap="companyMap">
select * from ss_company
</select>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/192579.html
標籤:其他
下一篇:使用powerdesigner繪制物理模型生成sql檔案,ODBC資料源連接MySQL驅動方式,powerdesigner的使用
