1.通过学生查询教师信息,使用一对多的第一种方法。
2.实例展示:
问题描述:
通过学生sid查询老师信息。
数据库e-r图:
代码实现:
学生实体类Student.java:将教师实体类的集合作为学生的属性。
private List<Teacher> teachers; public List<Teacher> getTeachers() { return teachers; } public void setTeachers(List<Teacher> teachers) { this.teachers = teachers; }
StuentDao.java层方法:
//通过学生sid查出老师 Student getStudentById(int sid);
StuddentMapper.xml文件核心内容:
collection标签内column属性值为传入下句sql语句的字段属性名。
property属性值为student实体类中teacher集合的属性名。<mapper namespace="com.zx.dao.StudentDao"> <select id="getStudentById" resultMap="studentResult"> select * from student where sid=#{sid} </select> <resultMap id="studentResult" type="com.zx.pojo.Student"> <id column="sid" property="sid"></id> <result column="sname" property="sname"></result> <!--集合映射 collection标签内column属性值为传入下句sql语句的字段属性名。 property属性值为student实体类中teacher集合的属性名。 --> <collection column="sid" property="teachers" select="com.zx.dao.TeacherDao.getTeachersBySid" ofType="com.zx.pojo.Teacher" ></collection> </resultMap> </mapper>
TeacherDao.java层方法:
List<Teacher> getTeachersBySid(int sid);
TeacherMapper文件:通过中间表查询满足条件的教师信息
<mapper namespace="com.zx.dao.TeacherDao"> <!--通过学生sid找老师——通过中间表--> <select id="getTeachersBySid" resultType="com.zx.pojo.Teacher"> select * from teacher where tid in (select tid from student_teacher where sid=#{sid}) </select> </mapper>
Mybatis-config.xml添加sql映射:
<mappers> <mapper resource="com/zx/dao/StudentMapper.xml"></mapper> <mapper resource="com/zx/dao/TeacherMapper.xml"></mapper> </mappers>
运行测试:
public class StudentDaoTest { @Test public void getStudentByIdTest(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); StudentDao studentDao = sqlSession.getMapper(StudentDao.class); Student student = studentDao.getStudentById(2); System.out.println(student); //通过Teachers属性的get方法读取教师信息 System.out.println(student.getTeachers()); } }
测试结果: