【问题标题】:How to turn on eager initialization in Hibernate throught method calling如何通过方法调用在 Hibernate 中打开急切初始化
【发布时间】:2014-07-14 15:18:50
【问题描述】:

休眠中加载的默认实体设置为惰性。我想在方法调用时打开 Hibernate 中的急切初始化,然后仍然使用延迟加载:

例如我有这样的实体:

 public class Applications  implements java.io.Serializable {


     private int id;
     private String name;
     private Set viewses = new HashSet(0); // here entities views
     private Set routeses = new HashSet(0);  // here antoher entities routes

     public Set getViewses() {
        return this.viewses;
     }

     public void setViewses(Set viewses) {
        this.viewses = viewses;
     }

     public Set getRouteses() {
        return this.routeses;
     }

     public void setRouteses(Set routeses) {
        this.routeses = routeses;
     }

     // .... other things

 } 

我想避免迭代所有内部对象以完全获取有关对象应用程序的所有详细信息例如:

        begin();
        List apps = getSession().createQuery("from Applications").list(); // here lazy initalisation not all inner elements are filled from database
        commit();

上面的代码导致(路由,视图)等内部实体为空。 当我调用 application.getRouteses() 时没有任何反应,因为我已将惰性设置为 true,并且在会话关闭(提交)后调用 getRouteses() 唯一的方法是通过一个事务在实体应用程序中设置所有元素并从方法中完全返回它是使用迭代和设置器或急切初始化:

        begin();
        List apps = getSession().createQuery("from Applications").list();
        Iterator iter = apps.iterator();
        while(iter.hasNext()){
            Applications application = (Applications) iter.next();
            application.setRouteses(application.getRouteses()); // here i set all routes beacuse i call getRoutes and hibernate will load from db
        }
        commit();

现在急切地安装,下面的代码也会加载有关具有内部路由和视图实体的对象的所有详细信息:

        begin();
        List apps = getSession().createQuery("from Applications").list(); // here eager all inner object are filled from databasse
        commit();

唯一的问题是将惰性更改为渴望,但在 hibernate.xml 配置中没有。我想知道是否可以在 Eager 上运行一段时间,然后打开惰性(程序化)。例如:

        // HERE LAZY INITIALISATION
        turnOnEager(); // some method ???

        // HERE EAGER INITIALISATION
        begin();

        List apps = getSession().createQuery("from Applications").list(); // here eager all inner object are filled from databasse
        commit();

        // AND LAZY AGAIN
        turnOnLazy(); // some method ???

【问题讨论】:

    标签: java spring hibernate


    【解决方案1】:

    您不能在运行时打开和关闭惰性。但是,您可以尝试使用 fetch 关键字更改 hql 以获取子实体,如下所示。

    HQL

    from Applications a join fetch a.someProperty s join fetch s.anotherProperty
    

    来自文档:

    “获取”连接允许关联或值集合 使用单个选择与其父对象一起初始化。 这在集合的情况下特别有用。它 有效地覆盖了外部连接和惰性声明 关联和集合的映射文件。

    参考:http://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/queryhql.html

    【讨论】:

      猜你喜欢
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      相关资源
      最近更新 更多