您的位置:宽带测速网 > 编程知识 > MyBatis中怎么进行多对多关联查询

MyBatis中怎么进行多对多关联查询

2025-06-23 19:43来源:互联网 [ ]

在MyBatis中进行多对多关联查询可以通过使用<collection><association>标签来实现。

假设有两个实体类AuthorBook,它们之间是多对多的关系,一个作者可以写多本书,一本书也可以由多个作者共同写作。首先需要在AuthorBook的Mapper文件中配置关联查询的SQL语句:

<!-- AuthorMapper.xml --><select id="getAuthorById" resultType="Author" parameterType="int">SELECT * FROM author WHERE id = #{id}</select><select id="getBooksByAuthorId" resultType="Book" parameterType="int">SELECT b.* FROM book bJOIN author_book ab ON b.id = ab.book_idWHERE ab.author_id = #{authorId}</select><!-- BookMapper.xml --><select id="getBookById" resultType="Book" parameterType="int">SELECT * FROM book WHERE id = #{id}</select><select id="getAuthorsByBookId" resultType="Author" parameterType="int">SELECT a.* FROM author aJOIN author_book ab ON a.id = ab.author_idWHERE ab.book_id = #{bookId}</select>

然后在Author和Book实体类中定义关联的属性:

public class Author {private Integer id;private String name;private List<Book> books;// 省略getter和setter方法}public class Book {private Integer id;private String title;private List<Author> authors;// 省略getter和setter方法}

最后在MyBatis配置文件中配置关联查询的映射:

<!-- AuthorMapper.xml --><resultMap id="AuthorResultMap" type="Author"><id property="id" column="id" /><result property="name" column="name" /><collection property="books" ofType="Book" resultMap="BookResultMap" /></resultMap><!-- BookMapper.xml --><resultMap id="BookResultMap" type="Book"><id property="id" column="id" /><result property="title" column="title" /><collection property="authors" ofType="Author" resultMap="AuthorResultMap" /></resultMap>

通过以上配置,就可以在AuthorMapper和BookMapper中查询到多对多关联的数据,并且在返回结果中包含关联的实体对象列表。