1. 程式人生 > >mybitis中對象字段與表中字段名稱不匹配(復制)

mybitis中對象字段與表中字段名稱不匹配(復制)

復制 diamond ocl value bat lai shape tag where

開發中,實體類中的屬性名和對應的表中的字段名不一定都是完全相同的,這樣可能會導致用實體類接收返回的結果時導致查詢到的結果無法映射到實體類的屬性中,那麽該如何解決這種字段名和實體類屬性名不相同的沖突呢?

方法一:通過在查詢的SQL語句中定義字段名的別名的方式,讓字段名的別名和實體類中的屬性名一致,這樣就可以實現實體類屬性和表字段一一對應。(通過在SQL語句中定義別名的方法實現)

[html] view plain copy
  1. <select id="queryCertificationInfoByCerNumber" parameterType="string" resultMap="certificationResultMap">
  2. SELECT cer_number cerNumber FROM, cer_time cerTime, cer_type cerType t_diamond_allinfo_gia WHERE cer_number = #{cerNumber}
  3. </select>

方法二:通過<resultMap>來映射字段名和實體類屬性名的一一對應關系。(使用Mybatis提供的解決方法)

[html] view plain copy
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    4. <mapper namespace="com.jqscm.mapper.SearchMapper">
    5. <select id="queryCertificationInfoByCerNumber" parameterType="string" resultMap="certificationResultMap">
    6. SELECT * FROM t_diamond_allinfo_gia WHERE cer_number = #{cerNumber}
    7. </select>
    8. <!-- 通過resultMap映射實體類和表字段的關系 -->
    9. <resultMap type="CertificationInfo" id="certificationResultMap">
    10. <!-- 用id屬性來映射主鍵字段 -->
    11. <id property="cerNumber" column="cer_number"/>
    12. <!-- 用result屬性來映射非主鍵字段 -->
    13. <result property="cerTime" column="cer_time"/>
    14. <result property="cerType" column="cer_type"/>
    15. <result property="shape" column="shape"/>
    16. <result property="size" column="size"/>
    17. </resultMap>
    18. </mapper>

mybitis中對象字段與表中字段名稱不匹配(復制)