resultmap和resulttype的一些使用誤區

mybatis的映射配置文件中的兩個返回值類型resultmap和resulttype;

直接來測試代碼:

<select id="getUser" parameterType="string" resultType="pojo.User">
	select id,username,userpwd from t_users where id=#{id}
</select>

這是正確的,resulttype在這裏是類的全類名,這樣執行沒有任何問題;


結果就是我們想要的。

接下來我們來定義一個<resultMap>:

<resultMap id="user" type="pojo.User" >  
    <id column="id" property="id"  />  
    <result column="username" property="username" />  
    <result column="userpwd" property="userpwd"  /> 
  </resultMap> 

然後我們修改一下上面的配置:

<select id="getUser" parameterType="string" resultMap="user">
	select id,username,userpwd from t_users where id=#{id}
</select>

我們把resulttype改成resultmap然後取了<resultMap>中的id;運行結果也是正常的;跟上面打印的是一樣的;

接下來看一下他們之間的不同點:


當看到這種錯誤的時候,就說明用的resulttype指定到<resultMap>中的id上去了;

  <select id="getUser" parameterType="string" resultType="user" >
		select id,username,userpwd from t_users where id=#{id}
	</select>
想讓上面的配置起作用該怎麼改?那就是使用別名:在mybatis-config.xml中加入
<typeAliases>
	<typeAlias alias="user" type="pojo.User"/>
</typeAliases>

這裏的alias就是resulttype的值;

以上只是我們書寫時容易注意不到的部分;

注意:mybatis返回的類型:那一定是map類型了,就是鍵值對的形式返回數據;但是我們使用resulttype時,會把map中的值取出來賦值給對象的屬性;

發佈了42 篇原創文章 · 獲贊 17 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章