MyBatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap,resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,
但是resultType跟resultMap不能同时存在。
在MyBatis进行查询映射时,其实每一个查询映射的返回类型都是ResultMap,只是当提供的返回类型属性是resultType的时候,MyBatis对自动的给把对应的值赋给resultType所指定对象的属性。
1)resultType:通常对于简单查询;
2)resultMap:通常对于复杂查询;
1、resultType示例:
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>
2)返回实体list:
<typeAlias alias="Blog" type="com.tiantian.mybatis.model.Blog"/> <select id="selectBlog" resultType="Blog"> select * from t_blog </select>
2、resultMap:
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>
同样,可以接受单个实体,也可以接受实体list;
2)复杂查询:
<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 属性。
扫描二维码关注公众号,回复:
1096256 查看本文章