建立POJO对象,都省略类 set和get方法。 Grade.java
public class Grade implements Serializable{ private Integer c_id; private String code; private String name; //班级和学生一对多的关系,一个班级可以有多个学生 private List<Student> students; }Student.java
public class Student implements Serializable { private Integer s_id; private String s_name; private String sex; private Integer age; }映射文件GradeMapper.xml
<mapper namespace="com.stumybatis.dao.GradeDao"> <select id="selectGradeById" parameterType="int" resultMap="gradeStudent"> SELECT * from f_class c,f_student s where c.c_id=#{c_id} and s.class_id=c.c_id </select> <resultMap id="gradeStudent" type="com.stumybatis.pojo.Grade"> <id property="c_id" column="c_id"/> <result property="code" column="code"/> <result property="name" column="name"/> <!--collection表示一对多的关系--> <collection property="students" ofType="com.stumybatis.pojo.Student" > <id property="s_id" column="s_id"/> <result property="s_name" column="s_name"/> <result property="sex" column="sex"/> <result property="age" column="age"/> </collection> </resultMap> </mapper>GradeDao接口的内容
public interface GradeDao { public Grade selectGradeById(Integer c_id); }测试代码
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring-mybatis.xml"}) public class StudentDaoTest { @Autowired private GradeDao gradeDao; @Test public void testSelecGrade2() throws Exception{ Grade grade = gradeDao.selectGradeById(1); System.out.println(grade.getC_id()+ " "+grade.getCode()+" "+grade.getName()); List<Student> list = grade.getStudents(); for(Student student:list){ System.out.println(student); } }结果如下: 但是有一个特别好玩的就是,如果这两个地方的name不区分的话,那就会有很有意思的结果,就是所有的s_name都写成name,会出现下图的结果。把学生的name全都变成了软件工程。很神奇有没有。
这里的环境是搭建好的SSM环境测试的。