作者:fyupeng
技术专栏:☞ https://github.com/fyupeng
项目地址:☞ https://github.com/fyupeng/distributed-blog-system-api
留给读者
一、介绍
比如你需要在Company
对象中,嵌套一个或多个SonCompany
和ContactInfo
,也就是联合使用一对多和多对一的对象关系。
而且还是直接通过数据库查询出来,不想自己遍历去构造这种对象,那么你可以使用MyBatis
的association
和collection
关键字。
提示:association
标签必须放在 collection
上方,
二、代码
public Class Company {
private SonCompany sonCompany;
private List<ContactInfo> contactInfos;
<select id="queryCompanyDataByKey" resultMap="CompanyItemMap">
select * from (
select a.id, a.area, a.uniscid, a.updatetime as updateTime, b.area as sonArea, b.uniscid as sonUniscid, c.name as contactName
from company a inner join son_comopany b on a.sonId = b.id
inner join contact_info c on a.contact_id = c.id
)
</select>
<resultMap id="CompanyItemMap" type="com.fyupeng.company">
<id property="id" column="id" />
<result property="area" column="area" />
<result property="uniscid" column="uniscid" />
// 子公司
<result property="updateTime" column="updateTime" />
<association property="sonCompany" javaType="com.fyupeng.SonCompany">
<result property="sonArea" column="sonArea" />
<result property="sonUniscid" column="sonUniscid" />
</association>
// 联系人信息
<collection property="contactInfos" ofType="com.fyupeng.ContactInfo">
<result property="contactName" column="contactName" />
</collection>
</resultMap>
三、总结
简洁、高效、实用!