简体   繁体   English

使用Hibernate防止无限循环数据检索

[英]Preventing infinite loop data retrieval with Hibernate

I was wondering: Imagine a scenario where eg 我在想:想象一个场景,例如

//POJO // 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. 想象一下,这些对象已正确映射到它们各自的Hibernate配置文件中。

My question: 我的问题:

How would I retrieve my user with the list of all the user blogs on code level? 如何在代码级别上用所有用户博客的列表检索用户? (ie, not allow hibernate to populate blogList automatically for me. I want to add paging (ie 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. (即,不允许休眠状态自动为我填充blogList 。我想添加分页(即从列表5中检索20个列表),而且,如果您仔细考虑,这可能是一个无限循环,因为Blog具有一个User实体,有一个List<Blog>实体。

How do I prevent this? 我该如何预防?

PS Just out of curiousity, how would I let Hibernate populate my blogList on the configuration side? PS刚出于好奇,我将如何让Hibernate在配置侧填充我的blogList

Thanks in advance. 提前致谢。

  • Hibernate detects such loops and doesn't let them happen Hibernate会检测到这样的循环,并且不会让它们发生
  • 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 您可以使用fetch type = lazy( fetchType=FetchType.LAZY )来标记您的集合,以便在拥有对象fetchType=FetchType.LAZY不提取集合元素。
  • you can used a Query with setFirstResult(..) and setMaxResults(..) in order to achieve paging. 您可以将QuerysetFirstResult(..)setMaxResults(..)使用以实现分页。 (and get rid of the collection then) (然后删除集合)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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