zoukankan      html  css  js  c++  java
  • 什么情况下用resultType和 resultMap

    MyBatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap
    
    那什么情况下用resultType?
    resultMap 一般用在什么情况下?
     
    如果你搜索只是返回一个值,比如说String ,或者是int,那你直接用resultType就行了。
    但是你如果是返回一个复杂的对象,就必须定义好这个对象的resultMap的result map。
     
    举个例子吧,例子以ibatis为例:
    你有个User 对象, 拥有两个字段id,name。 
    1.你要获取id为123的name
    String name = (String) queryForObject("getUserNameByID", id);
     
    <select id="getUserNameByID" resultType="java.lang.String">
     Select name from User where id =#id#
     </select>
     
    2.你要获取整个User对象
    User user = (User) queryForObject("getUserByID", id);
     
    <resultMap class="包.User" id="User">
      <result property="id" column="ID" />
      <result property="name" column="NAME" />
     </resultMap>
     
    <select id="getUserByID" resultMap="User">
     Select ID,NAME from User where id =#id#
     </select>
    追问
    但是,resultType 也可以返回一个对象 
    <select id="getUserNameByID" resultType="com.bean.User">
    Select * from User where id =#id#
    </select>
    
    也可以返回一个封装的对象啊
    这个跟resultMap是一样的效果
    那什么时候是用resultType解决不了的呢?只能用resultMap
    回答
    你要是反回这个对象用result type,就必须返回这个对象所有信息了,而且没有任何设置,适用用普通的完整返回。
     
    但你用resultmap,因为resultmap,因为resultmap那段是我们自己指定的,可能指定的属性只是User的一部分,而且还可以设置默认值,这是result type做不到的:
    resultMap里面只定义 name
    <resultMap class="包.User" id="User">
      <result property="name" column="NAME" />
     </resultMap>
     
    <select id="getUserByID" resultMap="User">
     Select NAME from User where id =#id#
     </select>
  • 相关阅读:
    卡特兰数
    Tree
    关于树上DP的转移方式与复杂度证明
    Tarjan进阶
    排队
    Perm 排列计数
    [bzoj1227]虔诚的墓主人
    [BZOJ1195]最短母串
    ValueError: Variable vgg_16/conv1/conv1_1/weights already exists, disallowed
    《链家网技术架构的演进之路》读后感
  • 原文地址:https://www.cnblogs.com/linjiaxin/p/7481731.html
Copyright © 2011-2022 走看看