数据库实体 多对一实现 和一对多
多对一
public class Student {
private int id;
private String name;
private Teacher teacher;// 表示 student 对 teacher是多对一。
public class Teacher {
private int id;
private String name;
表结构如下:
<!--多对一查询 --> <select id="getStudents2" resultMap="studentTeacher"> select s.id sId, s.name sName ,t.id tId,t.name tName from student s, teacher t where s.tid = t.id </select> <!-- 多对一查询 方法一:使用级联属性的方式 因为 tId是 Teacher类的 id属性,而 Student类有Teacher类的属性叫 teacher 所以可以属性级联:teacher.id --> <resultMap id="studentTeacher" type="Student"> <result property="id" column="sId"></result> <result property="name" column="sName"></result> <result property="teacher.id" column="tId"></result> <result property="teacher.name" column="tName"></result> </resultMap>
方法二:
<resultMap id="studentTeacher2" type="Student">
<result property="id" column="sId"></result>
<result property="name" column="sName"></result>
<association property="teacher" javaType="Teacher">
<id column="tId" property="id"></id> <!--id 如果不配置的话,默认返回0-->
<result column="tName" property="name"></result>
</association>
</resultMap>
一对多
public class Teacher {
private int id;
private String name;
private List<Student> student;
public class Student {
private int id;
private String name;
private int tId;
表结构和上图一样
<select id="getTeachers" resultMap="teacherStudentMap"> select t.id tId, t.name tName, s.id sId, s.name sName, s.tid sTid from teacher t,student s where t.id = s.tid; </select> <resultMap id="teacherStudentMap" type="Teacher"> <result column="tId" property="id" ></result> <result column="tName" property="name"></result> <collection property="student" ofType="Student"> <result column="sId" property="id"></result> <result column="sName" property="name"></result> <result column="sTid" property="tId"></result> </collection> </resultMap>

浙公网安备 33010602011771号