背景: 一个存在多对一的映射的表结构,比如视频和视频上传者,目前想取出最受欢迎的视频并要求显示视频的上传者的名字,传统的做法往往会存在n+1问题,对性能有些影响
在IBatis中如何做?马上进入实战
配置文件如下:
<?
xml version="1.0" encoding="UTF-8"
?>
<! DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-2.dtd" >
< sqlMap namespace ="specialtopic" >
.................................
< resultMap id ="top-Video-column1" class ="moxtv.central.po.Video" >
< result property ="videoId" column ="videoId" />
< result property ="title" column ="title" />
< result property ="timeSpan" column ="timeSpan" />
< result property ="user.loginName" column ="loginName" />
< result property ="videoReport.viewedCount" column ="viewedCount" />
</ resultMap >
< statement id ="getTopVideoListByColumn1" resultMap ="top-Video-column1" cacheModel ="getTopVideoListByColumn1-cache" >
select v.videoId,v.title,v.timeSpan,tu.loginName,vr.viewedCount
from top_baby_video tbv
inner join video v on tbv.videoId=v.videoId
inner join video_report vr on v.videoId=vr.videoId
inner join tvUser tu on v.tvUserId=tu.tvUserId
</ statement >
............................
</ sqlMap >
<! DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-2.dtd" >
< sqlMap namespace ="specialtopic" >
.................................
< resultMap id ="top-Video-column1" class ="moxtv.central.po.Video" >
< result property ="videoId" column ="videoId" />
< result property ="title" column ="title" />
< result property ="timeSpan" column ="timeSpan" />
< result property ="user.loginName" column ="loginName" />
< result property ="videoReport.viewedCount" column ="viewedCount" />
</ resultMap >
< statement id ="getTopVideoListByColumn1" resultMap ="top-Video-column1" cacheModel ="getTopVideoListByColumn1-cache" >
select v.videoId,v.title,v.timeSpan,tu.loginName,vr.viewedCount
from top_baby_video tbv
inner join video v on tbv.videoId=v.videoId
inner join video_report vr on v.videoId=vr.videoId
inner join tvUser tu on v.tvUserId=tu.tvUserId
</ statement >
............................
</ sqlMap >
我们采用多表关联的方式用一个sql取出所有数据,然后定义我们映射规则(见上面的 resultMap段),从规则中可以看出,我们将从查出来的loginName列映射到video中复杂属性user的loginName属性.这样的话,一句sql 就把所需要的 video对象完整加载了, 避免了n+1问题.
resultMap是一个非常好的咚咚,比起hibernate它或许多余,但却给了你更大的自由,来配置关系和对象之间的映射规则.而且也无需担心在使用hibernate2中多对一自动加载