開發中,實體類中的屬性名和對應的表中的字段名不一定都是完全相同的,這樣可能會導致用實體類接收返回的結果時導致查詢到的結果無法映射到實體類的屬性中,那么該如何解決這種字段名和實體類屬性名不相同的沖突呢?
方法一:通過在查詢的SQL語句中定義字段名的別名的方式,讓字段名的別名和實體類中的屬性名一致,這樣就可以實現實體類屬性和表字段一一對應。(通過在SQL語句中定義別名的方法實現)
<select id="queryCertificationInfoByCerNumber" parameterType="string" resultMap="certificationResultMap"> SELECT cer_number cerNumber FROM, cer_time cerTime, cer_type cerType t_diamond_allinfo_gia WHERE cer_number = #{cerNumber} </select> 方法二:通過<resultMap>來映射字段名和實體類屬性名的一一對應關系。(使用Mybatis提供的解決方法)
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.jqscm.mapper.SearchMapper"> <select id="queryCertificationInfoByCerNumber" parameterType="string" resultMap="certificationResultMap"> SELECT * FROM t_diamond_allinfo_gia WHERE cer_number = #{cerNumber} </select> <!-- 通過resultMap映射實體類和表字段的關系 --> <resultMap type="CertificationInfo" id="certificationResultMap"> <!-- 用id屬性來映射主鍵字段 --> <id PRoperty="cerNumber" column="cer_number"/> <!-- 用result屬性來映射非主鍵字段 --> <result property="cerTime" column="cer_time"/> <result property="cerType" column="cer_type"/> <result property="shape" column="shape"/> <result property="size" column="size"/> </resultMap></mapper>
新聞熱點
疑難解答