用Hibernate防止无限循环数据检索 [英] Preventing infinite loop data retrieval with Hibernate

查看:118
本文介绍了用Hibernate防止无限循环数据检索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道:假设一个场景,例如

// POJO

  public class User {

private String userName;
私人字符串名称;
私人字符串姓氏;
私人列表< Blog> blogList;

//在这里找到所有获得者和设置者,并假设他们已经生成。
}

public class Blog {
private String title;
私人字符串内容;
私人用户作者;
私人日期datePublished;
私人日期dateLastModified;

//所有getter和setter都已经生成(通过Eclipse或NetBeans)
}

想象一下,这些对象已被正确映射到它们各自的Hibernate配置文件中。



我的问题:

我如何检索我的用户,并在代码级别列出所有用户博客? (即,不允许hibernate自动为我填充 blogList
我想添加分页(即从列表5中检索20列表),并且如果您仔细想想,这可能是一个无限循环,因为Blog有一个用户实体,它有一个 List< Blog> 实体。



如何防止这种情况发生?



PS只是出于好奇,我如何让Hibernate在配置端填充我的 blogList



预先感谢。

解决方案


  • Hibernate检测到这样的循环并且不让它们发生。可以使用fetch type = lazy( fetchType = FetchType.LAZY )标记您的集合,以便在拥有对象

  • 时不会获取集合元素
  • 可以通过 setFirstResult(..) setMaxResults()来使用 Query 。 。)为了实现分页。(并且摆脱co然后选择)


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.

解决方案

  • 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)

这篇关于用Hibernate防止无限循环数据检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆