mybatis,xml查询的实体类返回带有list集合的查询方法

当xml需要返回的实体类中的属性有List<Object>如何实现

  1. 首先我的实体类1是这样的。我们主要处理的是实体类的中List

    @Data
    public class MsgBoard {
        private String msgid;
        private String muserid;
        private String mcontent;
        private Date mpostime;
        private List<ReplyMsg> replyMsgList; 
    
    }
    
    
  2. 实体类2

    @Data
    public class ReplyMsg {
           private String reid;
           private String msgid;
           private Date rpostime;
           private String rcontent;
           private String ruserid;
    }
    
  3. 这里Controller、Service层的查询我们就忽略的。主要展示mapper层的xml配置

     <!--MsgBoard-->
        <resultMap id="MsgBoardResult" type="com.ice.bean.MsgBoard">
            <result column="msg_id" jdbcType="VARCHAR" property="msgid" />
            <result column="muser_id" jdbcType="VARCHAR" property="muserid" />
            <result column="mcontent" jdbcType="VARCHAR" property="mcontent" />
            <result column="mpostime" jdbcType="VARCHAR" property="mpostime" />
            <collection property="replyMsgList" ofType="com.ice.bean.ReplyMsg"
                        column="msg_id" select="selectReplyById">
            </collection>
        </resultMap>
       <!--ReplyMs-->
        <resultMap id="ReplyMsgResult" type="com.ice.bean.ReplyMsg">
            <result column="re_id" jdbcType="VARCHAR" property="reid" />
            <result column="msg_id" jdbcType="VARCHAR" property="msgid" />
            <result column="rpostime" jdbcType="VARCHAR" property="rpostime" />
            <result column="rcontent" jdbcType="VARCHAR" property="rcontent" />
            <result column="ruser_id" jdbcType="VARCHAR" property="ruserid" />
        </resultMap>
    
    
  4. 主要是通过collection这里进行配置

    <!--其中property对应的是MsgBoard类中的集合属性名,
    ofType是集合对应的类型这里是ReplyMsg,
    column是查询这个(ReplyMsg)集合是需要的MsgBoard对应的参数,即查询传递的参数, 本例中是msgid
    select对应的是查询的语句 同一个mapper的画直接写id就可以.不同的需要补全路径-->
    <collection property="replyMsgList" ofType="com.ice.bean.ReplyMsg"
                        column="msg_id" select="selectReplyById">
    </collection>
    
  5. 具体的mapper查询如下

     <!--查询MsgBoard-->
        <select id="getMsg" resultMap="MsgBoardResult">
            select * from msg_board
        </select>
        <!-- 查询MsgResult-->
        <select id="selectReplyById" resultMap="ReplyMsgResult" >
            select * from reply_msg where msg_id=#{msgid}
        </select>
    
  6. 这样我们接到的实体类的字段中的集合就有参数了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章