MyBatis注解開發的兩種方法@Results和resultMap


在使用mybatis注解開發的時候,數據庫返回的結果集和實體類字段不對應,我們就需要手動指定映射關系;

 一種是使用在xml文件中指定resultMap,指定id,下面需要的直接引用id就可以;

<mapper namespace="dao.test">
    <resultMap id="resultMap" type="edu.com.bean.Message">
        <id property="id" column="id"/>
        <result property="name" column="nname"/>
        <result property="mail" column="mail"/>
    </resultMap>
        <select id="findAll" resultMap="resultMap">
            select * from mybatis_test;
        </select>
</mapper>

 

  另一種在使用注解開發的時候,我們只能通過注解@Results來指定對應關系了,那么注解只能每個方法用到了都得復制一遍@Results嗎?答案當然不是,注解@Results中提供了id屬性這就跟xml文件中的id作用一樣,下面引用的話可以用@ResultMap來引用。

        首先說明一下@Results各個屬性的含義,id為當前結果集聲明唯一標識,value值為結果集映射關系,@Result代表一個字段的映射關系,column指定數據庫字段的名稱,property指定實體類屬性的名稱,jdbcType數據庫字段類型,@Result里的id值為true表明主鍵,默認false;使用@ResultMap來引用映射結果集,其中value可省略。

//聲明結果集映射關系代碼:
@Select("select * from mybatis_test where id = #{id}") @Results(id = "Message" , value = { @Result(column="id", property="id"), @Result(column="nname", property="name"), @Result(column="mail", property="mail") }) public Message getMessageById(Integer id); //引用結果集代碼: @Select("select * from mybatis_test") @ResultMap(value = "Message") public List<Message> findAll();

注: 只有先聲明之后,后面才能調用,否則會報錯:Result Maps collection does not contain value for XXXXX。

這樣我們就不用每次需要聲明結果集映射的時候都復制冗余代碼,簡化開發,提高了代碼的復用性。

 具體詳細參考一下兩個鏈接

鏈接參考:https://blog.csdn.net/qq_40348465/article/details/84715198

     https://blog.csdn.net/qq_37394874/article/details/86074618


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM