【MyBatis】MyBatis之collection

MyBatis之collection

标签的用法,与相同,只是新增ofType属性,它用来将 JavaBean(或字段)属性的类型和集合存储的类型区分开来。

Book表数据

id author_id book_name
1 1 三国
2 1 水浒
3 2 红楼

Author表数据

id username password email bio
1 张三 1 1 2
2 李四 1 1 1
@Data
public class Book {

	private Integer id;

	private Integer authorId;

	private String bookName;
}
@Data
public class Author {

	private Integer id;

	private String username;

	private String password;

	private String bio;

	private String email;
	
	private List<Book> books;
}

集合的嵌套结果映射

<select id="selectAuthor" resultMap="authorResultMap" >
    select 
    a.id,a.username,a.password,email,a.bio,
    b.id as book_id,b.author_id,b.book_name
    from author a left join book b 
    on a.id = b.author_id
</select>
	<resultMap id ="authorResultMap" type="Author">
		<id property="id" column="id"/>
		<result property="username" column="username"/>
		<result property="password" column="password	"/>
		<result property="email"    column="email"/>
		<result property="bio"      column="bio"/>
		<collection property="books" ofType="Book" column="author_id">
			<id property="id" column="book_id"/>
			<id property="authorId" column="author_id"/>
			<id property="bookName" column="book_name"/>
		</collection>
	</resultMap>

集合的嵌套 Select 查询

<resultMap id ="authorResultMap2" type="Author">
		<id property="id" column="id"/>
		<result property="username" column="username"/>
		<result property="password" column="password	"/>
		<result property="email"    column="email"/>
		<result property="bio"      column="bio"/>
		<collection property="books" ofType="Book" select="selectBooks" column="{authorId=id}">
		</collection>
</resultMap>
<resultMap  id ="bookMap"         type="Book">
		<id     property="id"          column="id" />
		<result property="bookName"    column="book_name" />
		<result property="authorId"    column="author_id" />
</resultMap>
<select id ="selectBooks" resultMap="bookMap">
		select * from book where author_id = #{authorId}
	</select>
<select id="selectAuthor2" resultMap="authorResultMap2">
    select * from author
</select>
<!-- 前缀拦截-->
<resultMap id ="authorResultMap4" type="Author">
		<id property="id" column="id"/>
		<result property="username" column="username"/>
		<result property="password" column="password	"/>
		<result property="email"    column="email"/>
		<result property="bio"      column="bio"/>
		<collection property="books" ofType="Book"	resultMap="bookMap" columnPrefix="bk_" >
		</collection>
	</resultMap>
	
   <resultMap  id ="bookMap"         type="Book">
		<id     property="id"          column="id" />
		<result property="bookName"    column="book_name" />
		<result property="authorId"    column="author_id" />
	</resultMap>

代码地址:https://gitee.com/firefish/mybatis_study

摘抄:https://mybatis.org/mybatis-3/zh/sqlmap-xml.html

posted @ 2022-03-10 23:36  二月无雨  阅读(6032)  评论(0编辑  收藏  举报