【MyBatis】MyBatis之collection
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>
好学若饥,谦卑若愚
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?