一、引言
一直對association和collection有點混淆,現整理一篇文章,用於加強記憶。
二、association
association用於一對一、多對一場景使用。
現在有2個表book表、bookshelf書架表。
BOOK | ||
字段名稱 | 類型 | 備註 |
id | int | 主鍵 |
name | varchar | 書名 |
type | int | 類型 |
shelf_id | int | 書架id |
Book_shelf | ||
字段名稱 | 類型 | 備註 |
id | int | 主鍵 |
number | varchar | 書架編號 |
num | int | 可存放數量 |
現有需求:查詢根據書籍id查詢書籍信息和所在書架編號。
PoJo
public class Book{
private Integer id;
private String name;
private String type;
private Integer shelfId;
private BookShelf bookShelfDto;
}
public class BookShelf {
private Integer id;
private String number;
private String num;
}
mapper
<resultMap id="bookResultMap" type="com.abc.Book">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="type" column="type"/>
<!--關聯屬性-->
<association property="bookShelfDto" javaType="com.abc.BookShelf">
<id property="id" column="shelf_id"/>
<result property="number" column="number"/>
<result property="num" column="num"/>
</association>
</resultMap>
<select id="getBookInfo" resultMap="bookResultMap">
select book.id,book.name,book.type,book.shelf_id,shelf.number,shelf.num
from book left join book_shelf shelf on book.shelf_id = shelf.id
where book.id = #{id}
</select>
三、collection
應用場景爲一對多關係,即實體裏放集合。
表不變
現有需求:根據書架ID查詢書架信息及書架存放的書籍信息。
POJO
public class Book{
private Integer id;
private String name;
private String type;
private Integer shelfId;
}
public class BookShelf {
private Integer id;
private String number;
private String num;
private List<Book> bookList;
}
<resultMap id="bookShelfResultMap" type="com.abc.BookShelf">
<id property="id" column="shelf_id"/>
<result property="number" column="number"/>
<result property="num" column="num"/>
<!--關聯屬性-->
<collection property="bookList" javaType="com.abc.Book">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="type" column="type"/>
</collection>
</resultMap>
<select id="getBookShelfInfo" resultMap="bookShelfResultMap">
select book.id,book.name,book.type,book.shelf_id,shelf.number,shelf.num
from book left join book_shelf shelf on book.shelf_id = shelf.id
where shelf.id = #{id}
</select>
Mapper.java
BookShelf getBookShelfInfo(Integer id);