當(dāng)查詢結(jié)果的列名和java對象的屬性名對應(yīng)不上時需要采用下列方式進行處理:
????????第一種方式:在查詢語句中使用關(guān)鍵字"as" 給列起別名
????????第二種方式:使用resultMap結(jié)果映射
????????第三種方式:開啟駝峰命名自動映射(配置settings)
實體類Car:
package com.bjpowernode.domain;
public class Car {
??? private Integer id;
??? private String carNum;
??? private String brand;
??? private Double guidePrice;
??? private String produceTime;
??? private String carType;
//構(gòu)造方法略
//setter and getter 略
//toString略
數(shù)據(jù)庫中的t_car表:
我們可以看出實體類中的屬性名與數(shù)據(jù)庫表中的字段名并不完全一樣,需要進行處理,三種處理方式如下:
第一種方式:在查詢語句中使用關(guān)鍵字"as" 給列起別名,所起的別名需要是實體類的屬性名
<select id="selectById" resultType="com.powernode.mybatis.pojo.Car">
??????? select
??????????? id,
??????????? car_num as carNum,
??????????? brand,
??????????? guide_price as guidePrice,
??????????? produce_time as produceTime,
??????????? car_type as carType
??????? from
??????????? t_car
?? ?????where
??????????? id = #{id}
??? </select>
第二種方式:采用resultMap結(jié)果映射,具體如下:
<!--
?resultMap:
?????? id:是這個結(jié)果映射的唯一標(biāo)識,
?????? type:結(jié)果集要映射的類(也就是對應(yīng)的實體類)。可以使用別名。
-->
<resultMap id="carResultMap" type="car">
?????????<!--id是對象的唯一標(biāo)識,為了提高mybatis的性能。建議寫上。-->
?????????<id property="id" column="id"/>
?????????<result property="carNum" column="car_num"/>
?????????<!--當(dāng)屬性名和數(shù)據(jù)庫列名一致時,可以省略。但建議都寫上。-->
?????????<!--javaType用來指定屬性類型。jdbcType用來指定列類型。一般可以省略。-->
?????????<result property="brand" column="brand" javaType="string" jdbcType="VARCHAR"/>
?????????<result property="guidePrice" column="guide_price"/>
?????????<result property="produceTime" column="produce_time"/>
?????????<result property="carType" column="car_type"/>
</resultMap>
<!--resultMap屬性的值必須和resultMap標(biāo)簽中id屬性值一致。-->
<select id="selectAllByResultMap" resultMap="carResultMap">
??????? select * from t_car
</select>
第三種方式:開啟駝峰命名自動映射(配置settings)
使用這種方式的前提是:
????????屬性名遵循Java的命名規(guī)范,數(shù)據(jù)庫表的列名遵循SQL的命名規(guī)范。
Java命名規(guī)范:
? ? ? ? 首字母大寫,后面每個單詞首字母大寫,遵循駝峰命名規(guī)范。
SQL命名規(guī)范:
????????全部小寫,單詞之間采用下劃線分割。
比如以下的對應(yīng)關(guān)系:
????????實體類中的屬性名??????????? ?????????????????數(shù)據(jù)庫表的列名
????????????????carNum ????????????????????????????????????????car_num
????????????????carType? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?car_type
????????????????produceTime? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?produce_time
啟用該功能,需要在mybatis-config.xml文件中進行如下配置:
<!--放在properties標(biāo)簽后-->
<settings>
?????? <setting name="mapUnderscoreToCamelCase" value="true"/>文章來源:http://www.zghlxwxcb.cn/news/detail-494719.html
</settings>文章來源地址http://www.zghlxwxcb.cn/news/detail-494719.html
到了這里,關(guān)于數(shù)據(jù)庫中的字段名與實體類中的屬性名不能一一對應(yīng)時的三種處理方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!