mybatis什么時候用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>

 


免責聲明!

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



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