區別:
兩者都可以用於映射文件中的<select>語句的返回值,但是兩者在返回值上面是有區別的
如下面的兩個例子:
使用resultType的
舉個例子吧,例子以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>
使用resultMap的
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>
具體的這兩個的區別:
(1)如果你需要只是返回一個值,比如說String ,或者是int,那你直接用resultType就行了。
但是你如果是返回一個復雜的對象,就必須定義好這個對象的resultMap的result map。
(2)當然resultType返回一個對象的話也是可以的,見下面的例子:
resultType 也可以返回一個對象 <select id="getUserNameByID" resultType="com.bean.User"> Select * from User where id =#id# </select> 也可以返回一個封裝的對象啊 這個跟resultMap是一樣的效果
但是需要注意的是此時select查詢的字段只能是你想要的 此時的select所查詢的內容只能是所有的實體的屬性,如 * 而不能是部分 屬性,這就是和resultMap的另一個區別,
比如你想要返回user對象的name屬性,而不返回age屬性的話,用 resultType="com.bean.User" 是不行的,因為用resultType限定所有的屬性值,
但是你可以用resultMap可以輕松的解決
但你用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>
當然在我們書寫Mybatis的Dao映射文件的時候,有時候回不太清楚到底都應該寫哪些內容,此時大家可以按照下面的順序去書寫即可
當我們在使用resultMap的時候,如果映射的對象里面的某些屬性也是一個自定義的對象的話,那么此時應該在<resultMap id="...." Type="...">的內容可以添加上<.collecion>
具體的collection的標簽的用法見另一篇博客:https://www.cnblogs.com/isme-zjh/p/12496902.html