一的一方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(); }
结果: