MyBatis之collection
標簽的用法,與 相同,只是新增 ofType
屬性,它用來將 JavaBean(或字段)屬性的類型和集合存儲的類型區分開來。
Book表數據
id | author_id | book_name |
---|---|---|
1 | 1 | 三國 |
2 | 1 | 水滸 |
3 | 2 | 紅樓 |
Author表數據
id | username | password | 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>