日期:2014-05-17  浏览次数:20717 次

关于Hibernate中的findbyexample方法
两个表,Item(id、fid);File(id、name)。设置了File的id和fid的关联,hibernate中为one-to-many 
用Item的getFile().getName()方法可以获取到File的name属性。hibernate配置应该没问题lazy设为false。 

但用findByExample查找时,找到了多余的数据。代码如下: 
Item item=new Item(); 
item.setFid(fdao.findById(new Integer(100))); //fdao是FileDAO对象 
List list=dao.findByExample(item);//dao是ItemDAO对象 
这样list里面会找出fid不是100的其他数据。。
如果给item设置其他值,比如setName(),设置没有关联其他表的字段值,findByExample查找时是有效的。就是设置外键关联的字段时就无效了,不知什么原因
大家帮帮忙,我看论坛上有类似的帖子,问题都没解决

------解决方案--------------------
由于看不到你的findById(),不能解答你的问题。先提供一种解决方案供参考:

List list=session.createQuery("from Item i left join fatch i.File"+
"where i.fid=100")
for(Iterator it=list.iterator(); it.hasNext();){
Item item=(Item)it.next();
.........
}