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 属性。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赶路人儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值