如下:User用户和Post帖子是一对多的关系,
public class User implements Serializable{
private int id;
private String username;
private String mobile;
private List<Post> posts;
}
public class Post implements Serializable{
private int id;
private User user;
private String title;
private String content;
}
1.那么在查一个用户以及他的多个文章时
<!-- User 级联文章查询 方法配置 (一个用户对多个文章) -->
<resultMap type="User" id="resultUserMap">
<result property="id" column="user_id" />
<result property="username" column="username" />
<result property="mobile" column="mobile" />
<collection property="posts" ofType="com.yiibai.pojo.Post" column="userid">
<id property="id" column="post_id" javaType="int" jdbcType="INTEGER"/>
<result property="title" column="title" javaType="string" jdbcType="VARCHAR"/>
<result property="content" column="content" javaType="string"
jdbcType="VARCHAR"/>
</collection>
</resultMap>
<!--查询语句-->
<select id="getUser" resultMap="resultUserMap" parameterType="int">
SELECT u.*,p.*
FROM user u, post p
WHERE u.id=p.userid AND id=#{user_id}
</select>
使用collection来对应User中的List;
2.查询帖子及其作者时
<resultMap type="Post" id="resultPostsMap">
<result property="id" column="post_id" />
<result property="title" column="title" />
<result property="content" column="content" />
<association property="user" javaType="User">
<id property="id" column="userid"/>
<result property="username" column="username"/>
<result property="mobile" column="mobile"/>
</association>
</resultMap>
<!--查询语句-->
<select id="getPosts" resultMap="resultPostsMap" parameterType="int">
SELECT u.*,p.*
FROM user u, post p
WHERE u.id=p.userid AND p.post_id=#{post_id}
</select>
即:collection是一对多的关系,association是一对一或者多对一的关系。