<resultMap type="com.foo.bean.BlogInfo" id="BlogInfo">
<id column="blog_id" property="blogId" />
<result column="title" property="title" />
<association property="author" column="blog_author_id"
javaType="com.foo.bean.Author" select="com.foo.bean.AuthorMapper.selectByPrimaryKey">
</association>
<collection property="posts" column="blog_id" ofType="com.foo.bean.Post"
select="com.foo.bean.PostMapper.selectByBlogId">
</collection>
</resultMap>
<select id="queryBlogInfoById" resultMap="BlogInfo" parameterType="java.math.BigDecimal">
SELECT
B.BLOG_ID,
B.TITLE,
B.AUTHOR_ID AS BLOG_AUTHOR_ID
FROM LOULUAN.BLOG B
where B.BLOG_ID = #{blogId,jdbcType=DECIMAL}
</select>
此方法的缺点:要进行n+1将查询
重新定义BlogInfo的结果映射 resultMap
<resultMap type="com.foo.bean.BlogInfo" id="BlogInfo">
<id column="blog_id" property="blogId"/>
<result column="title" property="title"/>
<association property="author" column="blog_author_id" javaType="com.foo.bean.Author">
<id column="author_id" property="authorId"/>
<result column="user_name" property="userName"/>
<result column="password" property="password"/>
<result column="email" property="email"/>
<result column="biography" property="biography"/>
</association>
<collection property="posts" column="blog_post_id" ofType="com.foo.bean.Post">
<id column="post_id" property="postId"/>
<result column="blog_id" property="blogId"/>
<result column="create_time" property="createTime"/>
<result column="subject" property="subject"/>
<result column="body" property="body"/>
<result column="draft" property="draft"/>
</collection>
</resultMap>
对应的sql语句如下:
<select id="queryAllBlogInfo" resultMap="BlogInfo">
SELECT
B.BLOG_ID,
B.TITLE,
B.AUTHOR_ID AS BLOG_AUTHOR_ID,
A.AUTHOR_ID,
A.USER_NAME,
A.PASSWORD,
A.EMAIL,
A.BIOGRAPHY,
P.POST_ID,
P.BLOG_ID AS BLOG_POST_ID ,
P.CREATE_TIME,
P.SUBJECT,
P.BODY,
P.DRAFT
FROM BLOG B
LEFT OUTER JOIN AUTHOR A
ON B.AUTHOR_ID = A.AUTHOR_ID
LEFT OUTER JOIN POST P
ON P.BLOG_ID = B.BLOG_ID
</select>
此方法是从数据库中将数据全部查询出来,然后对返回的结果集在内存中进行组装、赋值
嵌套查询
最新推荐文章于 2022-04-24 17:51:54 发布