一对多:
1,在一的model里定义ArrayList<多的对象>
2,在service里写方法:根据一的id或其他,查询出所有的多的list,赋值一的对象的属性值为多的List
如:
一的bean:
public class TopicModel {
private Integer id;
private String title;
private String content;
private Integer userId;
private ArrayList<TopicCommentModel> commentList;
public ArrayList<TopicCommentModel> getCommentList() {
return commentList;
}
public void setCommentList(ArrayList<TopicCommentModel> commentList) {
this.commentList = commentList;
}
service中实现关联
public TopicModel findByIdWithCommeents(Integer id) {
//自己发多次请求组装数据
TopicModel topic = mapper.selectOne(id);
List<TopicCommentModel> comments = commentMapper.selectAllByTopicId(topic.getId());
topic.setCommentList(new ArrayList<>(comments));
return topic;
}
2,或者在mapper中用联表查询实现
用resultMap定义一的bean,映射到
mapper中查询的函数的返回类型为包含多的一的bean
<resultMap id="selectOneWithCommentsMap" type="kybmig.ssm.model.TopicModel">
<id property="id" column="id" />
<result property="title" column="title" />
<result property="content" column="content" />
<collection property="commentList" ofType="kybmig.ssm.model.TopicCommentModel">
<id property="id" column="c_id" />
<result property="content" column="c_content" />
</collection>
</resultMap>
<select id="selectOneWithComments" resultMap="selectOneWithCommentsMap">
SELECT
Topic.id,
Topic.title,
Topic.content,
TopicComment.id as c_id,
TopicComment.content as c_content
FROM
ssm.Topic left join TopicComment
on Topic.id = TopicComment.topicId
where Topic.id = #{id}
</select>
resultMap的使用
,映射到type对应的bean
,<collection>集合
,<assosication>对象
<resultMap id="sselectOneWithCommentsAndUserMap" type="kybmig.ssm.model.TopicModel">
<id property="id" column="id" />
<result property="title" column="title" />
<result property="content" column="content" />
<collection property="commentList" ofType="kybmig.ssm.model.TopicCommentModel">
<id property="id" column="c_id" />
<result property="content" column="c_content" />
<association property="user" column="u_username" javaType="kybmig.ssm.model.UserModel">
<result property="username" column="u_username" />
</association>
</collection>
</resultMap>