【问题标题】:Hibernate retrieving parent/children休眠检索父/子
【发布时间】:2016-03-14 00:28:28
【问题描述】:

那么当我有一个一对多的双向关系时,我该如何确保我根据需要从数据库中获取它们?

例如:

在父类中:

@OneToMany(mappedBy="parent")
List<Child> children;

在子类中:

@ManyToOne
@JoinColumn(name="Parent_Id")
Parent parent;

我只是不确定如何确保当我拥有父级时,我可以获得其子级的列表,反之亦然。不确定 Hibernate 是如何处理的。

如果要孩子,我的第一反应是:

String hql="FROM Parent WHERE id=:id";
Query query = session.createQuery(hql);
query.setInteger("id", id);
Parent p = (Parent)query.uniqueResult();
List<Child>=p.getChildren();

反之亦然:

//insert retrieve child code
Parent p = child.getParent();

我的困惑是我不确定 Hibernate 是否真的在创建时用它们的父/子填充对象,如果是这样,我不确定检索它们的最有效方法。

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    关系的每一方都可以配置为渴望或懒惰。如果它是急切的,Hibernate 将在加载包含对象时立即加载该对象。如果它是惰性的,Hibernate 会放入一个占位符代理对象,并且该代理对象会在您第一次访问它时自动加载真实的(前提是会话/事务仍然打开,否则它会抛出一个LazyInitializationException)。无论哪种方式,访问关系的语法都是相同的 - p.getChildren()child.getParent() 在这两种情况下都适用。

    哪个选项最有效取决于您个人用例的详细信息。特别是,相对于加载包含对象的频率,您需要关系的频率(惰性允许您跳过不必要的加载),可能是多个关系引用单个对象的频率(取决于实现,eager 可能会检查数据库表即使对象已经加载并在内存中),以及您是否需要在关闭会话后访问关系。

    【讨论】:

    • 那么,如果我设置其中之一,我就不必编写代码来修饰数据库并填写它们了吗?
    • @user3478947 无论您是否设置它们,它们都是为您设置的。 ManyToOne 默认为 eager,OneToMany 默认为 lazy。不,无论您选择什么设置,您都不必编写代码来修饰数据库并填写它们。
    • 非常感谢。你刚刚度过了我的夜晚
    【解决方案2】:
    All things depend upon your configuration.If you will apply lazy loading then hibernate internally fetch the record from query at the time of getting the record except its identity.
    You can see the 
    Fetching Strategies
    There are four fetching strategies
    
    1. fetch-“join” = Disable the lazy loading, always load all the collections and entities.
    2. fetch-“select” (default) = Lazy load all the collections and entities.
    3. batch-size=”N” = Fetching up to ‘N’ collections or entities, *Not record*.
    4. fetch-“subselect” = Group its collection into a sub select statement.
    
    
    If you want to surety that what is happening internally in hibernate then Please enable
    <!--hibernate.cfg.xml -->
    <property name="show_sql">true</property>
    
    after enable you can see all queries in console.  
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      相关资源
      最近更新 更多