美文网首页
mybatis association , collectio

mybatis association , collectio

作者: 轻狂探花 | 来源:发表于2018-11-13 16:30 被阅读0次

    自己记录一下

    定义User ,Record
    public class User {
        private String user_id;
        private String user_name;
        private List<Record> recordList;
        private Record record;
    }
    
    public class Record {
        private String record_id;
        private String record_name;
    }
    
    <resultMap id="userMap" type="com.air.manager.pojo.agent.User">
            <id column="USER_ID" property="user_id" jdbcType="VARCHAR" />
            <result column="USER_NAME" property="user_name" jdbcType="VARCHAR" />
    
            // 一、关联单个对象 association ,如果关联对象超过一个会报错  
            //方法1 使用select属性查找selectRecordByUserId去加载
            <association property="record" column="USER_ID" select="selectRecordByUserId"/>
    
            //方法2 直接在内部定义record属性
            <association property="record" javaType="com.air.manager.pojo.agent.Record" >
                <id column="RECORD_ID" property="record_id" jdbcType="VARCHAR" />
                <result column="RECORD_NAME" property="record_name" jdbcType="VARCHAR" />
            </association >
    
            // 二、关联对象集合 collection
            //方法1 使用select属性查找selectRecordByUserId去加载
            <collection property="recordList" column="USER_ID" select="selectRecordByUserId"/>
    
            //方法2 直接在内部定义recordList集合 ,javaType="java.util.ArrayList"可以不添加
            <collection property="recordList" ofType="com.air.manager.pojo.agent.Record"  javaType="java.util.ArrayList" >
                <id column="RECORD_ID" property="record_id" jdbcType="VARCHAR" />
                <result column="RECORD_NAME" property="record_name" jdbcType="VARCHAR" />
            </collection>
    </resultMap>
    
    
    <select id="queryList" resultMap="userMap">
             SELECT 
                 T.USER_ID ,
                 T.USER_NAME
             FROM KING_USER T 
    </select>
    
    <resultMap id="recordMap" type="com.air.manager.pojo.agent.Record">
            <id column="RECORD_ID" property="record_id" jdbcType="VARCHAR" />
            <result column="RECORD_NAME" property="record_name" jdbcType="VARCHAR" />
    </resultMap>
        
    <select id="selectRecordByUserId" resultMap="recordMap">
            SELECT  
             R.RECORD_ID,
             R.RECORD_NAME
            FROM KING_RECORD R WHERE R.USER_ID=#{userId} //这里的userId名称可以随意,一样可以取到值
    </select>
    

    相关文章

      网友评论

          本文标题:mybatis association , collectio

          本文链接:https://www.haomeiwen.com/subject/madlfqtx.html