1. 程式人生 > 其它 >當實體類屬性和資料庫表的列名不一致時

當實體類屬性和資料庫表的列名不一致時

當實體類屬性和資料庫表的列名不一致時:

第一種:使用別名查詢

<!-- 配置查詢所有操作 -->
<select id="findAll" resultType="com.xxx.pojo.User">
select id as userId,username as userName,birthday as userBirthday,
sex as userSex,address as userAddress from user
</select>

第二種:使用resultMap方法

<!-- 建立 User 實體和資料庫表的對應關係type 屬性:指定實體類的全限定類名id 屬性:給定一個唯一標識,是給查詢 select 標籤引用用的。-->
<resultMap type="com.xxx.pojo.User" id="userMap">
    <id column="id" property="userId"/>
    <result column="username" property="userName"/>
    <result column="sex" property="userSex"/>
    <result column="address" property="userAddress"/>
    <result column="birthday" property="userBirthday"/>
</resultMap>
id 標籤:用於指定主鍵欄位
result 標籤:用於指定非主鍵欄位
column 屬性:用於指定資料庫列名
property 屬性:用於指定實體類屬性名稱

那麼對映配置就要呼叫(resultMap="userMap")就行;

<!-- 配置查詢所有操作 -->
<select id="findAll" resultMap="userMap">
	select * from user
</select>

結果就出來了。兩種各有優點:

方法一:速度快;

方法二:簡便,直接呼叫就行。