Forzar la carga ansiosa de propiedades cargadas de otro modo perezosas


Tengo un objeto de hibernación cuyas propiedades están cargadas perezosamente. La mayoría de estas propiedades son otros objetos Hibernados o conjuntos persistentes.

Ahora quiero forzar la Hibernación para cargar estas propiedades por una sola vez.

Por supuesto que podría "tocar" cada una de estas propiedades con object.getSite().size() pero tal vez hay otra manera de lograr mi objetivo.

Author: Willi Mentzel, 2010-10-14

7 answers

La documentación lo pone así:

Puede forzar la búsqueda ansiosa habitual de propiedades usando fetch all properties en HQL.

Referencias

 7
Author: Pascal Thivent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-14 13:24:29

Esta es una vieja pregunta, pero también quería señalar el método estático Hibernate.initialize.

Ejemplo de uso:

Person p = sess.createCriteria(Person.class, id);
Hibernate.initialize(p.getChildren());

Los hijos ahora se inicializan para ser utilizados incluso después de que se cierre la sesión.

 20
Author: stephen.hanson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-09 09:29:48

Dozer funciona bien para este tipo de cosas - puede pedirle a Dozer que mapee el objeto a otra instancia de la misma clase, y Dozer visitará todos los objetos accesibles desde el objeto actual.

Ver esta respuesta a una pregunta similary mi respuesta a otra pregunta relacionada para más detalles.

 3
Author: matt b,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:30:04

Para mí esto funciona:

Person p = (Parent) sess.get(Person.class, id);
Hibernate.initialize(p.getChildren());

En lugar de esto:

Person p = sess.createCriteria(Person.class, id);
Hibernate.initialize(p.getChildren());
 1
Author: oomer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-26 00:47:07

3 formas

1.HQL con hijos de unión izquierda

2.setFetchMode después de createCriteria

3.Hibernación.inicializar

 1
Author: user3073309,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-02 13:11:42

Esto es lento, porque hace un viaje de ida y vuelta por cada elemento que necesita inicializar, pero hace el trabajo.

private void RecursiveInitialize(object o,IList completed)
{
    if (completed == null) throw new ArgumentNullException("completed");

    if (o == null) return;            

    if (completed.Contains(o)) return;            

    NHibernateUtil.Initialize(o);

    completed.Add(o);

    var type = NHibernateUtil.GetClass(o);

    if (type.IsSealed) return;

    foreach (var prop in type.GetProperties())
    {
        if (prop.PropertyType.IsArray)
        {
            var result = prop.GetValue(o, null) as IEnumerable;
            if (result == null) return;
            foreach (var item in result)
            {
                RecursiveInitialize(item, completed);
            }
        }
        else if (prop.PropertyType.GetGenericArguments().Length > 0)
        {
            var result = prop.GetValue(o, null) as IEnumerable;
            if (result == null) return;
            foreach (var item in result)
            {
                RecursiveInitialize(item, completed);
            }
        }
        else
        {
            var value = prop.GetValue(o, null);
            RecursiveInitialize(value, completed);
        }
    }
}
 0
Author: Joshua Grippo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-08 02:53:33

De acuerdo con los documentos de hibernación , debería poder deshabilitar la carga de propiedades perezosas configurando el atributo lazy en sus asignaciones de propiedades particulares:

<class name="Document">
  <id name="id">
    <generator class="native"/>
  </id>
  <property length="50" name="name" not-null="true"/>
  <property lazy="false" length="200" name="summary" not-null="true"/>
  <property lazy="false" length="2000" name="text" not-null="true"/>
</class>
 -1
Author: dogbane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-14 10:59:01