Mybatis(三)返回值
Mybatis返回值
MyBatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap,resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在。
在MyBatis进行查询映射时,其实查询出来的每一个属性都是放在一个对应的Map里面的,其中键是属性名,值则是其对应的值。
①当提供的返回类型属性是resultType时,MyBatis会将Map里面的键值对取出赋给resultType所指定的对象对应的属性。其实MyBatis的每一个查询映射的返回类型都是ResultMap,只是当提供的返回类型属性resultType的时候,MyBatis自动的给对应的值赋给resultType所指定对象的属性。
②当提供的返回类型是resultMap时,因为Map不能很好表示领域模型,就需要自己再进一步的把它转化为对应的对象,这常常在复杂查询中很有作用(association,Collection),
<resultMap type="com.softjx.model.User" id="UserMap"> <result column="t_id" property="id"/> <result column="t_username" property="username" /> <result column="t_password" property="password"/> </resultMap> <!-- 查询数据表中的所有记录,并封装User对象集合 --> <select id="selectAll" resultMap="UserMap"> select * from t_user </select> <!-- 根据id查询数据表中的一条记录,并封装User对象 --> <select id="selectById" resultMap="UserMap"> select * from t_user where t_id=#{id}; </select> //统计id>?记录数 public int coutUser(Integer id); //统计id>?记录数 <select id="coutUser" resultType="int"> select count(*) from t_user where t_id>#{id}; </select>