方式一:
<sqlMap namespace="author">
<typeAlias alias="author" type="Author" />
<typeAlias alias="book" type="Book" />
<resultMap class="author" id="authorResult">
<result property="id" column="id"/>
<result property="authorName" column="authorName"/>
<result property="description" column="description"/>
<result property="books" column="id" select="getBooksByAuthorId"/>
</resultMap>
<resultMap class="book" id="bookResult">
<result property="id" column="id" />
<result property="bookName" column="bookName"/>
<result property="price" column="price" />
<result property="shelve" column="shelve" />
<result property="authorId" column="authorId" />
</resultMap>
<select id="getBooksByAuthorId" parameterClass="int" resultMap="bookResult">
SELECT id,bookName,price,shelve,authorId FROM book WHERE authorId=#id#
</select>
<select id="getAuthor" parameterClass="java.util.Map" resultMap="authorResult">
SELECT id, authorName, description FROM author WHERE isDelete = 0
<dynamic prepend="">
<isNotNull property="authorName">
AND authorName LIKE '%$authorName$%'
</isNotNull>
</dynamic>
ORDER BY id LIMIT #start#, #end#
</select>
</sqlMap>
方式二:
<sqlMap namespace="author">
<typeAlias alias="author" type="Author" />
<typeAlias alias="book" type="Book" />
<resultMap class="author" id="authorResult">
<result property="id" column="id"/>
<result property="authorName" column="authorName"/>
<result property="description" column="description"/>
<result property="books" column="id" resultMap="bookResult"/>
</resultMap>
<resultMap class="book" id="bookResult">
<result property="id" column="bookId" />
<result property="bookName" column="bookName"/>
<result property="price" column="price" />
<result property="shelve" column="shelve" />
</resultMap>
<select id="getBooksByAuthorId" parameterClass="int" resultMap="bookResult">
SELECT id,bookName,price,shelve,authorId FROM book WHERE authorId=#id#
</select>
<select id="getAuthor" parameterClass="java.util.Map" resultMap="authorResult">
SELECT a.id, a.authorName, a.description,b.id as bookId,b.bookName,b.price,b.shelve FROM author a join book b on a.id=b.authorId WHERE a.isDelete = 0
<dynamic prepend="">
<isNotNull property="authorName">
AND a.authorName LIKE '%$authorName$%'
</isNotNull>
</dynamic>
ORDER BY a.id LIMIT #start#, #end#
</select>
</sqlMap>
方式一:结构清晰,但查询会有N+1的问题(主表查询一次,子表查询N次)。
方式二:是方式一的改进,一次查询出所有结果,性能更好,但结构复杂时不易维护。在子表信息查询次数较少时,通过使用ibatis的延迟加载机制方式一会比较高效。