Mybaits---关于关联表数据查询

<resultMap id="ResultListUser" type="com.cwh.model.User" >
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="userName" property="userName" jdbcType="VARCHAR"/>
        <result column="userAge" property="userAge" jdbcType="VARCHAR"/>
        <result column="userAddress" property="userAddress" jdbcType="VARCHAR"/>
    </resultMap>

       <resultMap type="com.cwh.model.Article" id="resultUserArticleList">
		<id column="id" property="id"/>
		<result column="title" property="title" />
        <result column="content" property="content" />
		<association property="user" javaType="com.cwh.model.User" resultMap="ResultListUser"/>
	</resultMap>
	
	
    	<select id="getUserArticles" parameterType="int" resultMap="resultUserArticleList">
		 select article.id,article.title,article.content, user.id,user.userName,user.userAddress from user,article
              where user.id=article.userid and user.id=#{id}
	</select>

关联查询有两种写法,主要用以上这种,这样代码复用性比较大,在用这种方式是需特别注意的一点就是在查询语句写时注意主表关系,以多的一方为主,查询语句写的时候必须以article表的字段写在前面。

如果顺序调反,像以下错误写法:(那么出现查询结果只有是一条数据)

	<select id="getUserArticles" parameterType="int" resultMap="resultUserArticleList">
		select  user.id,user.userName,user.userAddress,article.id,article.title,article.content from user,article
              where user.id=article.userid and user.id=#{id}
	</select>



修改一下,纠正下,其实存在这种问题是两张表都有同一个名的字段叫id,所以其实查询的时候把从表的ID这个字段另名一下就好了。


posted @ 2016-05-06 14:52  menco  阅读(8)  评论(0)    收藏  举报