Mybatis中的resultType和resultMap
MyBatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap,resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在。 通常情况:
- resultType:用于单表简单查询,或者是count等查询;
- resultMap:用于多表复杂查询,或者是使用了函数的sql查询;
1、resultType用法:
resultType可以是:int、string、class或者hashMap,接下来看一些例子:
1)返回单个实体;
<typeAlias alias="Blog" type="com.tiantian.mybatis.model.Blog"/>
<select id="selectBlog" parameterType="int" resultType="Blog">
select * from t_blog where id = #{id}
</select>
<!--或者-->
<select id="selectBlog2" parameterType="int" resultType="com.tiantian.mybatis.model.Blog">
select * from t_blog where id = #{id}
</select>
2)返回实体list:
<select id="selectBlogList" resultType="com.tiantian.mybatis.model.Blog">
select * from t_blog
</select>
可以看到,对于返回单个实体,实体集合的写法是一样的,mybatis会自动判断。
3)返回int类型:
<select id="selectBlogCount" resultType="java.lang.Integer">
select count(*) from t_blog
</select>
4)返回map类型:
<select id="selectBlog3" parameterType="int" resultType="java.util.Map">
select * from t_blog where id = #{id}
</select>
同理,也可以返回map集合,写法也是一样的。
2、resultMap用法:
resultMap通常是一个实体类型,也可以是map类型。例如:
1)实体类型:
<resultMap id="BaseResultMap" type="cn.edu.nuc.springbootmybatisdynamicmutilds.entity.Test">
<result column="id" property="id" javaType="string" jdbcType="VARCHAR"/>
<result column="name" property="name" />
</resultMap>
column:数据库中列名称,property:类中属性名称
<select id="findByName" resultMap="BaseResultMap" parameterType="java.lang.String">
select id,name from test where name = #{name}
</select>
同样,可以返回单个实体类型,也可以返回实体类型的集合,写法一样。
2)map类型:
<resultMap type="java.util.HashMap" id="TownMap">
<result column="townid" property="townid"/>
<result column="townname" property="townname"/>
</resultMap>
<select id="findTownList" resultMap="TownMap">
SELECT townid,townname from test
</select>
同样,可以返回单个map,也可以返回map类型的集合,写法一样。
3)复杂查询:
<resultMap id="blogResult" type="Blog">
<association property="author" column="author_id" javaType="Author" select="selectAuthor"/>
</resultMap>
<select id="selectBlog" resultMap="blogResult">
SELECT * FROM BLOG WHERE ID = #{id}
</select>
<select id="selectAuthor" resultType="Author">
SELECT * FROM AUTHOR WHERE ID = #{id}
</select>
我们有两个查询语句:一个来加载博客,另外一个来加载作者,而且博客的结果映射描 述了“selectAuthor”语句应该被用来加载它的 author 属性。
还没有评论,来说两句吧...