码迷,mamicode.com
首页 > 其他好文 > 详细

MyBatis注解开发的两种方法@Results和resultMap

时间:2020-05-05 12:37:30      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:result   指定   col   lis   nta   http   div   映射关系   where   

在使用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

MyBatis注解开发的两种方法@Results和resultMap

标签:result   指定   col   lis   nta   http   div   映射关系   where   

原文地址:https://www.cnblogs.com/shaoxiao666/p/12830073.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!