一对多

一对多:
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>


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值