在MyBatis中进行多对多关联查询可以通过使用<collection>
和<association>
标签来实现。
假设有两个实体类Author
和Book
,它们之间是多对多的关系,一个作者可以写多本书,一本书也可以由多个作者共同写作。首先需要在Author
和Book
的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 b
JOIN author_book ab ON b.id = ab.book_id
WHERE 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 a
JOIN author_book ab ON a.id = ab.author_id
WHERE 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中查询到多对多关联的数据,并且在返回结果中包含关联的实体对象列表。