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. 這樣我們接到的實體類的字段中的集合就有參數了

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