标签:映射 collection 查询 dept emp 集合 association emps
通过collection集合来解决一对多的映射关系
一对多:一个部门对应多个员工
多对一:多个员工对应一个部门
一对多的解决方法:
在部门(少的)的实体类中设置一个员工集合属性(多的)
private List<Emp> emps;
public List<Emp> getEmps() {
return emps;
}
public void setEmps(List<Emp> emps) {
this.emps = emps;
}
连表查询时:
<select id="getDeptAndEmp" resultMap="resultMapId">
select * from dept left join emp on dept.did = emp.did;
</select>
<resultMap id="resultMapId" type="com.simple.simple1.Dept">
<id property="did" column="did"></id>
<result property="dname" column="dname"></result>
<collection property="emps" ofType="Emp">
<id property="eid" column="eid"></id>
<result property="ename" column="ename"></result>
<result property="password" column="password"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
<result property="email" column="email"></result>
</collection>
</resultMap>
连表查询的时候,会查询到多条emp的具体记录,但是无法与dept实体类中的集合属性进行映射,所以使用的resultMap中的collection标签,来将集合中的emp实体类的属性与查询到的emp记录的字段名建立映射关系
分步查询时:
第一步:
查询指定dept记录,此时emp集合与没有映射关系,所以使用resultMap来进行分步查询,为emp集合赋值
<select id="getDeptAndEmp" resultMap="resultMapId">
select * from dept left join emp on dept.did = emp.did;
</select>
<resultMap id="resultMapId" type="com.simple.simple1.Dept">
<id property="did" column="did"></id>
<result property="dname" column="dname"></result>
</resultMap>
第二步:
dept中其余属性与字段名建立了映射,根据唯一标识,调用sql,传入外键(或者关联的键)去执行查找,并返回一个emp的集合
<association property="emps" select="com.simple.simple1.pojo.mapper.UserMapper.getEmpByDid" column="did">
<result property="ename" column="username"></result>
<result property="password" column="password"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
<result property="email" column="email"></result>
</association>
column="did" 外键(或者说是两个表相关联的键)
最后将集合里的实体类的属性名和查询出来的字段名建立映射关系即可
标签:映射,collection,查询,dept,emp,集合,association,emps 来源: https://www.cnblogs.com/new228666/p/16418089.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。