在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中查詢到多對多關聯的數據,并且在返回結果中包含關聯的實體對象列表。