mybatis:懒加载

968 阅读1分钟

懒加载定义

按需加载,需要的时候再加载

案例

以cid查询一个班级,然后得到班级的信息,但是暂时不获取student的信息,当用到student时才去查询数据

使用

在需要懒加载的select语句后: ,+fetchType= FetchType.LAZY

	//一对多
	//以班级id,找到该班级及所有的学生
	@Select("select * from clazz")   //cid cname
	@Results({
		@Result(id=true,column="cid",property="cid"),
		@Result(column="cname",property="cname"),
		@Result(column="cid",property="students",many=@Many(
			select="selectStudentsByCid",
			fetchType=FetchType.LAZY		//指定获取的类型为懒加载
		))
	})
	public List<Clazz> allClazz();

注意

mybatis里虽然用了fetchType,但是不管访问哪个属性,都会将所有属性的值查询出来,即是用了懒加载属性。 这时,需要在主配置文件 mabatis-config.xml的中添加:

<setting name="aggressiveLazyLoading" value="false"/>