1. 程式人生 > >resultmap和resulttype的一些使用誤區

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中的值取出來賦值給物件的屬性;