本文共 2204 字,大约阅读时间需要 7 分钟。
刚刚在学mybatis,谈下我队多对一单向映射的看法,新手,有错误请指出,
mybatis的实体映射是通过在外键表中引入主键表的实体类的,
比如主键表为tb_clazz,外键表为tb_student,学生表的clazz_id作为外键引用到tb_clazz,
那么实体映射表为:
public class Clazz {
private Integer id; private String code; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public String toString(){ return "["+id+","+code+"]"; } }public class Student {
private Integer id; private String name; private String sex; private Integer age; private Clazz clazz; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Clazz getClazz() { return clazz; } public void setClazz(Clazz clazz) { this.clazz = clazz; } @Override public String toString(){ return "["+id+","+name+","+sex+","+age+","+clazz.toString()+"]"; } }然后再xml中配置关系,通过resultMap实现
<resultMap type="org.fkit.domain.Student" id="studentResultMap">
<id property="id" column="id"/> <result property="name" column="name"/> <result property="sex" column="sex"/> <result property="age" column="age"/> <association property="clazz" column="clazz_id" javaType="org.fkit.domain.Clazz" select="selectClazzWithId" ></association> </resultMap> <select id="selectClazzWithId" resultType="org.fkit.domain.Clazz"> select * from tb_clazz where id=#{id} </select> <select id="selectStudent" resultMap="studentResultMap"> select * from tb_student </select>因为表中存储的是id,但是实体映射类中存储的是实体,所有先需要根据表的id查询到实例,
DEBUG [main] -==> Preparing: select * from tb_student
DEBUG [main] -==> Parameters: DEBUG [main] -====> Preparing: select * from tb_clazz where id=? DEBUG [main] -====> Parameters: 1(Integer) DEBUG [main] -<==== Total: 1 DEBUG [main] -====> Preparing: select * from tb_clazz where id=? DEBUG [main] -====> Parameters: 2(Integer) DEBUG [main] -<==== Total: 1 DEBUG [main] -<== Total: 4由日志信息可以知道,先是查询tb_student表,然后对于外键在进行查询,但是并不重复查询
转载地址:http://dpjqi.baihongyu.com/