您的位置:首页 > 其它

mybatis什么时候用resulttype 什么时候用resultmap

2018-01-10 11:19 429 查看
如果你搜索只是返回一个值,比如说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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: