tags:

views:

16

answers:

1

Hi everyone,

I was wondering: Imagine a scenario where e.g.

//POJO

public class User {

   private String userName;
   private String name;
   private String surname;
   private List<Blog> blogList;

   //All getters and setters are found here and assume they're generated.
}

public class Blog {
    private String title;
    private String content;
    private User author;
    private Date datePublished;
    private Date dateLastModified;

    //All getters and setters have been generated (by Eclipse or NetBeans)
}

Imagine that these objects have been correctly mapped into their respective Hibernate configuration files.

My question:

How would I retrieve my user with the list of all the user blogs on code level? (i.e., not allow hibernate to populate blogList automatically for me. I want to add paging (i.e. from list 5, retrieve 20 list) and also, if you think carefully, this might be an infinite loop as a Blog has a User entity which has a List<Blog> entity.

How do I prevent this?

PS Just out of curiousity, how would I let Hibernate populate my blogList on the configuration side?

Thanks in advance.

+3  A: 
  • Hibernate detects such loops and doesn't let them happen
  • You can mark your collection with fetch type=lazy (fetchType=FetchType.LAZY) so that the collection elements are not fetched when the owning object is
  • you can used a Query with setFirstResult(..) and setMaxResults(..) in order to achieve paging. (and get rid of the collection then)
Bozho
Beat me by 10 seconds. Nice.
aperkins
I get what you mean, so I guess it's bye, bye DAO's :)
The Elite Gentleman
What does `FetchType.LAZY` do?
The Elite Gentleman
it is by no means "bye" to DAOs. The DAOs use the session/entity manager, Query objects, etc. The service layer should not know of these. FetchType.LAZY means that collection is fetched only if it is accessed.
Bozho
OK...so would Hibernate know if the collection is accessed? by the `getBlogList()` method?
The Elite Gentleman
it creates a proxy around your list. So it becomes `PersistentList`, instead of `ArrayList` for example.
Bozho
I'm beginning to like Hibernate now.
The Elite Gentleman