Mybatis中的resultType和resultMap

素颜马尾好姑娘i 2021-06-24 15:59 615阅读 0赞

MyBatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap,resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在。 通常情况:

  • resultType:用于单表简单查询,或者是count等查询;
  • resultMap:用于多表复杂查询,或者是使用了函数的sql查询;

1、resultType用法:

resultType可以是:int、string、class或者hashMap,接下来看一些例子:

1)返回单个实体;

  1. <typeAlias alias="Blog" type="com.tiantian.mybatis.model.Blog"/>
  2. <select id="selectBlog" parameterType="int" resultType="Blog">
  3. select * from t_blog where id = #{id}
  4. </select>
  5. <!--或者-->
  6. <select id="selectBlog2" parameterType="int" resultType="com.tiantian.mybatis.model.Blog">
  7. select * from t_blog where id = #{id}
  8. </select>

2)返回实体list:

  1. <select id="selectBlogList" resultType="com.tiantian.mybatis.model.Blog">
  2. select * from t_blog
  3. </select>

可以看到,对于返回单个实体,实体集合的写法是一样的,mybatis会自动判断。

3)返回int类型:

  1. <select id="selectBlogCount" resultType="java.lang.Integer">
  2. select count(*) from t_blog
  3. </select>

4)返回map类型:

  1. <select id="selectBlog3" parameterType="int" resultType="java.util.Map">
  2. select * from t_blog where id = #{id}
  3. </select>

同理,也可以返回map集合,写法也是一样的。

2、resultMap用法:

resultMap通常是一个实体类型,也可以是map类型。例如:

1)实体类型:

  1. <resultMap id="BaseResultMap" type="cn.edu.nuc.springbootmybatisdynamicmutilds.entity.Test">
  2. <result column="id" property="id" javaType="string" jdbcType="VARCHAR"/>
  3. <result column="name" property="name" />
  4. </resultMap>

column:数据库中列名称,property:类中属性名称

  1. <select id="findByName" resultMap="BaseResultMap" parameterType="java.lang.String">
  2. select id,name from test where name = #{name}
  3. </select>

同样,可以返回单个实体类型,也可以返回实体类型的集合,写法一样。

2)map类型:

  1. <resultMap type="java.util.HashMap" id="TownMap">
  2. <result column="townid" property="townid"/>
  3. <result column="townname" property="townname"/>
  4. </resultMap>
  5. <select id="findTownList" resultMap="TownMap">
  6. SELECT townid,townname from test
  7. </select>

同样,可以返回单个map,也可以返回map类型的集合,写法一样。

3)复杂查询:

  1. <resultMap id="blogResult" type="Blog">
  2. <association property="author" column="author_id" javaType="Author" select="selectAuthor"/>
  3. </resultMap>
  4. <select id="selectBlog" resultMap="blogResult">
  5. SELECT * FROM BLOG WHERE ID = #{id}
  6. </select>
  7. <select id="selectAuthor" resultType="Author">
  8. SELECT * FROM AUTHOR WHERE ID = #{id}
  9. </select>

我们有两个查询语句:一个来加载博客,另外一个来加载作者,而且博客的结果映射描 述了“selectAuthor”语句应该被用来加载它的 author 属性。

发表评论

表情:
评论列表 (有 0 条评论,615人围观)

还没有评论,来说两句吧...

相关阅读