MyBatis学习笔记(三)关联关系映射

在学习mabatis 的过程中,接触到了关联关系映射,认为这是一个很重要的点,所以在这里做一个总结,进而强化知识。

关联关系映射我们说直白一点就是用于处理多表查询嗦得出的结果。此时,mybatis不能把结果集直接映射到我们的POJO上,所以,我们有一种方法便是创建一个VO对象,结果集里有什么列,VO对象里就有什么属性,以此来存放结果。

例如,查询博客表和用户表,一个博客有一个作者

select author.username blog.title from author inner join blog on author.id = blog.author_id where blog.id = 1

那么,VO对象里就应该是


此时VO对象就能接收结果集了

此外,还有一个方法是用的更多的,叫做resultMap,多种方式实现,先看看模型类的样子


一对一:第一种方式

<resultMap type="entity.Blog" id="blogMap">
	<!-- 基本属性 -->
	<id property="id" column="id"/>
	<result property="title" column="title"/>
	<!-- author_id作为外键的基本属性,建立关联联系,被关联属性取代 -->
	<!-- <result property="author_id" column="author_id"/> -->
	<!-- 关联属性:一对一 -->
	<association property="author" javaType="entity.Author">
		<!-- id:建立关系 -->
	        <id property="id" column="author_id"/>
		<result property="username" column="username"/>
		<result property="password" column="password"/>
		<result property="email" column="email"/>
		<result property="bio" column="bio"/>
	</association>
</resultMap>
<select id="findBlogInfo" parameterType="int" resultMap="blogMap">
	select blog.id blog_id,title,author_id,author.id,username,password,email,bio
	from blog left join author on blog.author_id = author.id
	where blog.id = #{id}
</select>

第二种方式就是使用两次resultMap,第一个用于映射关联属性,第二个只需要在association标签里指定接收上一个resultMap就行


第三种方式使用了两次查询,分别去查询两张表里的内容


一对多,与一对一很相似,方法也差不多,唯一不同的是association变成了collection

<resultMap type="entity.Blog" id="blogPostMap">
	<!-- 基本属性 -->
	<id property="id" column="blog_id"/>
	<result property="title" column="title"/>
	<!-- 关联属性:一对多 property的值是对象中的参数名,是一个List,ofType的值是集合里装的值的类型-->
	<collection property="postList" ofType="entity.Post">
		<id property="id" column="post_id"/>
		<result property="subject" column="subject"/>
		<result property="section" column="section"/>
		<result property="body" column="body"/>
	</collection>
</resultMap>
<select id="findBlogAndPost" parameterType="int" resultMap="blogPostMap">
	select blog.id blog_id,title,blog.author_id,post.id post_id,section,subject,body
	from blog left join post on blog.id = post.blog_id 
	where blog.id = #{id}
</select>

一对多加上一对一,直接把一对多加一对一的写法写上去,加一个extends就行


猜你喜欢

转载自blog.csdn.net/icydate/article/details/79951279