hibernate 一对多表查询时fetchMode.join 生成left outer join 出来数据重复问题
@OneToMany(cascade = CascadeType.ALL, mappedBy = "vote", fetch = FetchType.lazy) //fetch = FetchType.EAGER这样是否在session.find()时会马上关联查出子表呢?
@JoinColumn(name="voteId")
// Fetch策略定义
@Fetch(FetchMode.join)
//如果设FetchMode.join会生成left outer join语句,这样出来的结果,就可能重复,一条主表记录对多条子表记录
遍历时会有与子表数里相等的记录list
//所以可以用session.find(from model a where a.x=?)
//同时把fetch = FetchType.eager会执行查询主表和子表
Hibernate:
select
this_.voteId as voteId23_0_,
this_.arrangeMode as arrangeM2_23_0_,
this_.audit as audit23_0_,
this_.endTime as endTime23_0_,
this_.isopened as isopened23_0_,
this_.notice as notice23_0_,
this_.popularity as popularity23_0_,
this_.startTime as startTime23_0_,
this_.status as status23_0_,
this_.voteADNewName as voteADN10_23_0_,
this_.voteADOldName as voteADO11_23_0_,
this_.voteCity as voteCity23_0_,
this_.voteCompany as voteCom13_23_0_,
this_.voteInfoTitle as voteInf14_23_0_,
this_.voteLimit as voteLimit23_0_,
this_.voteMaker as voteMaker23_0_,
this_.voteMode as voteMode23_0_,
this_.voteName as voteName23_0_,
this_.votePicNewName as votePic19_23_0_,
this_.votePicOldName as votePic20_23_0_,
this_.voteProvince as votePro21_23_0_,
this_.voteRemark as voteRemark23_0_,
this_.voteType as voteType23_0_,
this_.voterInfo as voterInfo23_0_,
this_.voterName as voterName23_0_
from
Vote this_
where
this_.voteMaker=?
Hibernate:
select
votecustom0_.voteId as voteId1_,
votecustom0_.voteCustomApplyId as voteCust1_1_,
votecustom0_.voteCustomApplyId as voteCust1_26_0_,
votecustom0_.status as status26_0_,
votecustom0_.voteId as voteId26_0_,
votecustom0_.voteApplyName as voteAppl3_26_0_,
votecustom0_.voteApplyTypeId as voteAppl4_26_0_
from
VoteCustomApply votecustom0_
where
votecustom0_.voteId in (
select
this_.voteId
from
Vote this_
where
this_.voteMaker=?
)
order by
votecustom0_.voteCustomApplyId asc
//----页面取子表的数据时还是没有子表数据
如果用session.find("FROM Vote v left join fetch v.voteCustomApplys WHERE v.voteMaker='"+voteMaker+"'")
去倒页面还没不能加载到子表
必须把fetch = FetchType.eager