简体   繁体   中英

hibernate left join lazycollection untouchable

I got something like this:

Criteria crit = session.createCriteria(Parent.class,"p");
parentsList = crit.createCriteria(
    "childSet","c",
    JoinType.LEFT_OUTER_JOIN,
    Restrictions.eq("jt.2ndParentDto.pk2ndParentDto", pk2ndParent))
    .list();

My query returns a list of parents with one child each or none, i already tested the logged query directly, so i am pretty sure of it.

I have to retrieve a list of children, so i am adding the parent and creating the ones missing.

List<ChildDto> list=new ArrayList<ChildDto>();
for(ParentDto item:parentsList){
    Iterator<ChildDto> it=item.getChildSet().iterator();
    if(it.hasNext()){
        ChildDto dto = it.next();
        dto.setParentDto(item);
        list.add(dto);
    }
    else{
        ChildDto dto = new ChildDto();
        dto.setParentDto(item);
        list.add(dto);
    }
}
return list;

By calling item.getChildSet().iterator() hibernate loads the entire collection so i cannot call item.getChildSet().iterator().hasNext to check if there is something in the set, and i cannot call item.getChildSet().size() neither for the exact same reason...

then how?, what else is there?, i am currently out of ideas, how can i get the only item of the set if there is one?

Update : I just tried Extra lazy loading, but it doesn't change for better or worse...

item.getChildSet().iterator() still causes to load the entire collection.

And when i do item.getChildSet().size() hibernate triggers a count... so i always get size of the entire collection (no use).

And that's pretty much it =/

Update : I got it working with a projection by getting a list of Object[] items, and manually creating the classes. I don't like to do this because, with a change to the Hbm, you're forced to maintain queries of this kind, so i try to avoid this as much as possible.

我不确定我是否完全了解您的要求,但是我认为您正在寻找的是Hibernate的“额外懒惰”集合,该集合可让您获取有关集合的一些信息(包括大小),而无需初始化整个集合,以及将大型集合批量(而不是一次全部)加载到内存中。

Can you change the query to return the child records instead? That way you won't get the whole collection. I am not begin clear. Can you just get the child objects from the database, then call something like getParent() to get the parents you need?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM