首页 > 其他 > 详细

13、mybatis一对多resultMap中用collection指定集合的封装规则

时间:2020-02-23 16:22:28      阅读:549      评论:0      收藏:0      [点我收藏+]

一的一方College.java:

技术分享图片

 多的一方Student.java

技术分享图片

College的sqlmapper文件配置

    <resultMap type="com.pxxy.bean.College" id="collegeMap">
        <id column="id" property="id"/>
        <result column="collegeName" property="collegeName"/>
        
        <!-- collection定义关联集合类型的属性的封装规则 
                property:指定属性中集合的名称
                oftype:指定集合里面元素的类型;可以写别名-->
        <collection property="students" ofType="com.pxxy.bean.Student">
            <id column="s_id" property="id"/>
            <result column="name" property="name"/>
        </collection>
    </resultMap>
    
    <!-- 左连接查询 -->
    <select id="getColByIdPlus" resultMap="collegeMap">
        select c.id id,c.collegeName collegeName,s.id s_id,s.name name
        from college c
        left join student s
        on c.id = s.c_id
        where c.id=#{id}
    </select>

College的mapper接口方法

技术分享图片

 

 测试方法

    //测试根据id查询学校以及学校的学生
    @Test
    public void testGetColByIdPlus() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        CollegeMapper collegeMapper = sqlSession.getMapper(CollegeMapper.class);
        College college =  collegeMapper.getColByIdPlus(1);
        System.out.println(college);
        for(Student stu:college.getStudents()) {
            System.out.println(stu);
        }
        sqlSession.close();
    }

结果:

技术分享图片

 

13、mybatis一对多resultMap中用collection指定集合的封装规则

原文:https://www.cnblogs.com/lyh233/p/12350077.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!