数据库中的一对一,一对多,多对多
Java类中的一对一,一对多
如:
//旅游路线
public class Route {
//A
private int rid;//线路id,必输
private String rname;//线路名称,必输
...
//分类数据
private Category category; //B 一对一 association
//商家数据
private Seller seller;//C 一对一 association
//图片数据
private List<RouteImg> imgList; //集合 一对多 collection
通过resultMap 与association 与collection
简化了特殊类型的成员变量的查询与赋值
<!-- 要对当前这个route内部的其他的成员变量进行查询与赋值
select 指定接口方法使用到的语句
property指定需要查询的数据
column 指定select方法需要的参数
select 指定需要调用的dao方法
-->
<resultMap id="routeMap" type="route" autoMapping="true">
<association property="category" column="cid" select="com.wzx.dao.CategoryDao.findOneByCid" autoMapping="true"/>
<association property="seller" column="sid" select="com.wzx.dao.SellerDao.findOneBySid" autoMapping="true"/>
<collection property="imgList" column="rid" select="com.wzx.dao.RouteImgDao.findAllImgByRid" autoMapping="true"/>
</resultMap>
被简化的service方法
public Route findRouteById(int rid) {
//数据来自四个表,执行四个查找方法
//路线数据
RouteDao routeDao = MySessionUtils2.getMapper(RouteDao.class);
Route route =routeDao.findOneByRid(rid);
//通过assocication标签 与collection标签可以让mybatis帮我查询其他三个数据
//商家的数据 分类的数据,与图片集合的数据
return route;
}
延迟加载
- (1) 可以核心配置文件中设置全局设置也可以映射文件中设置局部设置
<settings>
<setting name="lazyLoadingEnabled" value="true" />
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
- (2) 对象的成员变量,只有被使用的时候才执行sql
- (3)
fetchType="eager"
立即查询 - (4)
fetchType="lazy"
延迟查询 如果调用到数据,就执行查询,否则不执行。
<resultMap id="routeMap" type="route" autoMapping="true">
<association property="category" column="cid" select="com.wzx.dao.CategoryDao.findOneByCid" autoMapping="true" fetchType="eager"/>
<association property="seller" column="sid" select="com.wzx.dao.SellerDao.findOneBySid" autoMapping="true" fetchType="eager"/>
<collection property="imgList" column="rid" select="com.wzx.dao.RouteImgDao.findAllImgByRid" autoMapping="true" fetchType="eager" />
</resultMap>