mybatis一对多collection select
mybatis一对多collection select
在MyBatis中,处理一对多关系时,通常会在映射文件中使用<collection>
元素,并在其中嵌套一个<select>
元素来实现对关联表的查询。这种方式允许你从一个表(称为“一”的一方)中查询数据,并同时获取与其关联的多个表(称为“多”的一方)中的数据。
下面是一个简化的例子,演示如何使用MyBatis的<collection>
和<select>
元素来处理一对多关系。
假设我们有两个表:Author
(作者)和Book
(书籍),一个作者可以有多本书。
数据库表结构
Author 表
id | name |
---|---|
1 | Author1 |
2 | Author2 |
Book 表
id | author_id | title |
---|---|---|
1 | 1 | Book1 by A1 |
2 | 1 | Book2 by A1 |
3 | 2 | Book1 by A2 |
实体类
Author.java
public class Author {
private Integer id;
private String name;
private List<Book> books;
// getters and setters
}
Book.java
public class Book {
private Integer id;
private Integer authorId;
private String title;
// getters and setters
}
Mapper 接口
AuthorMapper.java
public interface AuthorMapper {
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "books", column = "id",
many = @Many(select = "selectBooksByAuthorId"))
})
Author selectAuthor(Integer id);
List<Book> selectBooksByAuthorId(Integer authorId);
}
MyBatis 配置文件(XML 方式)
如果你不使用注解方式,也可以使用XML配置文件来实现相同的映射。
AuthorMapper.xml
<mapper namespace="com.example.AuthorMapper">
<resultMap id="AuthorResultMap" type="Author">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="books" ofType="Book" select="selectBooksByAuthorId" column="id"/>
</resultMap>
<select id="selectAuthor" resultMap="AuthorResultMap">
SELECT * FROM Author WHERE id = #{id}
</select>
<select id="selectBooksByAuthorId" parameterType="int" resultType="Book">
SELECT * FROM Book WHERE author_id = #{authorId}
</select>
</mapper>
使用方式
当你想要查询一个作者及其所有书籍时,你可以这样做:
// 获取 SqlSession(假设你已经配置好了 MyBatis)
SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
try {
AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
Author author = authorMapper.selectAuthor(1);
// 现在 author 对象中包含了 id, name 和 books 列表
} finally {
sqlSession.close();
}
在这个例子中,selectAuthor
方法会首先查询 Author
表,然后通过 selectBooksByAuthorId
方法查询与该作者关联的所有书籍,并将这些书籍设置到 Author
对象的 books
属性中。这就是 MyBatis 处理一对多关系的一种方式。