No cache version.

Caching disabled. Default setting for this page:enabled (code LNG204)
If the display is too slow, you can disable the user mode to view the cached version.

Vous devez être membre et vous identifier pour publier un article.
Les visiteurs peuvent toutefois commenter chaque article par une réponse.

Modifier le lazy loading avec Hibernate

Astuces de l’Infobrol (Java)Article publié le 28/04/2010 12:08:36


Généralités


Cet exemple fonctionne avec la version Hibernate 3.5.1-Final.
Il s’agit d’un aide mémoire pour moi, mais il peut servir à d’autres...

Procédure


RemoteLazyLoadCollectionCallback


  • Dans org.hibernate.collection , ajouter le package callback
  • Dans org.hibernate.collection.callback, ajouter la classe suivante :
    1. package org.hibernate.collection.callback;
    2.  
    3. import org.hibernate.collection.PersistentCollection;
    4. import org.hibernate.engine.SessionImplementor;
    5.  
    6. public interface RemoteLazyLoadCollectionCallback {
    7.  
    8. PersistentCollection lazyLoad(SessionImplementor session,
    9. PersistentCollection collection);
    10.  
    11. }


AbstractPersistentCollection


  • Dans org.hibernate.collection, ouvrir la classe AbstractPersistentCollection.

  • Ajouter un membre statique :
    1. private static RemoteLazyLoadCollectionCallback remoteLazyLoadCollectionCallback;
    2.  
    3. /**
    4. * @param remoteLazyLoadCollectionCallback the remoteLazyLoadCollectionCallback to set
    5. */
    6. public static synchronized void setRemoteLazyLoadCollectionCallback(
    7. RemoteLazyLoadCollectionCallback remoteLazyLoadCollectionCallback) {
    8. AbstractPersistentCollection.remoteLazyLoadCollectionCallback = remoteLazyLoadCollectionCallback;
    9. }
  • Ajouter un getter :
    1. private boolean isRemote() {
    2. return remoteLazyLoadCollectionCallback != null;
    3. }
  • Dans la méthode protected boolean readSize(), ajouter au début
    1. if (isRemote()) {
    2. initialize(true);
    3. }

    Faire de même pour toutes les méthodes readxxx.
  • Modifier la méthode protected final void initialize(boolean writing) comme ceci :
    1. protected final void initialize(boolean writing) {
    2. if (!initialized) {
    3. if (isRemote()) {
    4. remoteLazyLoadCollectionCallback.lazyLoad(session, this);
    5. setInitialized();
    6. } else {
    7. if (initializing) {
    8. throw new LazyInitializationException(
    9. "illegal access to loading collection");
    10. }
    11. throwLazyInitializationExceptionIfNotConnected();
    12. session.initializeCollection(this, writing);
    13. }
    14. }
    15. }

RemoteLazyLoadProxyCallback


  • Dans org.hibernate.proxy , ajouter le package callback
  • Dans org.hibernate.proxy.callback, ajouter la classe suivante :
    1. package org.hibernate.proxy.callback;
    2.  
    3. import java.io.Serializable;
    4.  
    5. import org.hibernate.engine.SessionImplementor;
    6.  
    7. public interface RemoteLazyLoadProxyCallback {
    8.  
    9. Object lazyLoad(SessionImplementor session, String entityName,
    10.  
    11. }

AbstractLazyInitializer


  • Dans org.hibernate.proxy, ouvrir la classe AbstractLazyInitializer
  • Ajouter un membre statique :
    1. private static RemoteLazyLoadProxyCallback remoteLazyLoadProxyCallback;
    2.  
    3. /**
    4. * @param remoteLazyLoadProxyCallback the remoteLazyLoadProxyCallback to set
    5. */
    6. public static synchronized void setRemoteLazyLoadProxyCallback(
    7. RemoteLazyLoadProxyCallback remoteLazyLoadProxyCallback) {
    8. AbstractLazyInitializer.remoteLazyLoadProxyCallback = remoteLazyLoadProxyCallback;
    9. }
    10. Ajouter un getter :
    11.  
    12. private boolean isRemote() {
    13. return (remoteLazyLoadProxyCallback != null);
    14. }
  • Ajouter un getter :
    1. private boolean isRemote() {
    2. return (remoteLazyLoadProxyCallback != null);
    3. }
  • Modifier la méthode public final void initialize() comme ceci :
    1. public final void initialize() throws HibernateException {
    2. if (!initialized) {
    3. if (isRemote()) {
    4. setImplementation(remoteLazyLoadProxyCallback.lazyLoad(session,
    5. entityName, id));
    6. } else {
    7. if ( session==null ) {
    8. throw new LazyInitializationException("could not initialize proxy - no Session");
    9. }
    10. else if ( !session.isOpen() ) {
    11. throw new LazyInitializationException("could not initialize proxy - the owning Session was closed");
    12. }
    13. else if ( !session.isConnected() ) {
    14. throw new LazyInitializationException("could not initialize proxy - the owning Session is disconnected");
    15. }
    16. else {
    17. target = session.immediateLoad(entityName, id);
    18. initialized = true;
    19. checkTargetState();
    20. }
    21. }
    22. }
    23. else {
    24. checkTargetState();
    25. }
    26. }


Exemple d’appel dans le client


  1. AbstractLazyInitializer
  2. .setRemoteLazyLoadProxyCallback(new MeatClientLazyLoadProxyCallback());
  3. AbstractPersistentCollection
  4. .setRemoteLazyLoadCollectionCallback(new MeatClientLazyLoadCollectionCallback());

Exemples d'implémentations des callbacks


  1. public class MeatClientLazyLoadProxyCallback implements
  2. RemoteLazyLoadProxyCallback {
  3.  
  4. public Object lazyLoad(SessionImplementor session, String entityName,
  5.  
  6. // Thread.dumpStack();
  7. Object result = ServiceLocator.getService(LazyInitFacade.class).get(entityName,
  8. id);
  9. if(result == null){
  10. LogFactory.getLog(getClass()).error(entityName+" - "+ id +" is NULL ‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹");
  11. }
  12. return result;
  13. }
  14.  
  15. }

  1. public class MeatClientLazyLoadCollectionCallback implements
  2. RemoteLazyLoadCollectionCallback {
  3.  
  4. @SuppressWarnings("unchecked")
  5. public PersistentCollection lazyLoad(SessionImplementor session,
  6. PersistentCollection collection) {
  7. PersistentCollection result = ServiceLocator.getService(
  8. LazyInitFacade.class).initializeCollection(collection, true);
  9. Field field;
  10. if (collection instanceof PersistentSet) {
  11. field = ReflectionUtils.findField(PersistentSet.class, "set",
  12. Set.class);
  13. } else if (collection instanceof PersistentBag) {
  14. field = ReflectionUtils.findField(PersistentBag.class, "bag",
  15. List.class);
  16. } else if (collection instanceof PersistentList) {
  17. field = ReflectionUtils.findField(PersistentList.class, "list",
  18. List.class);
  19. } else if (collection instanceof PersistentMap) {
  20. field = ReflectionUtils.findField(PersistentMap.class, "map",
  21. Map.class);
  22. } else {
  23. throw new RuntimeException(new NotSupportedException(collection
  24. .getClass()
  25. + " is not yet supported"));
  26. }
  27. Field snapshot = ReflectionUtils.findField(collection.getClass(),
  28. "storedSnapshot");
  29. if (snapshot != null) {
  30. ReflectionUtils.makeAccessible(snapshot);
  31. Object o = ReflectionUtils.getField(snapshot, collection);
  32. if (o == null) {
  33. ReflectionUtils.setField(snapshot, collection, new HashMap());
  34. }
  35. }
  36. ReflectionUtils.makeAccessible(field);
  37. ReflectionUtils.setField(field, collection, result);
  38. return result;
  39. }
  40.  
  41. }


Avatar :: Steph Un article de StephModifié 1 fois. (dernière modification le 03/05/2010 13:22:48 par Steph)



Source : indéterminée


Sélection, tri et recherche d'articles
FILTRER :
TRIER :1er critère : 2e critère :
CHERCHER : Dans les titres Dans le contenu


[Afficher les liens en fonction des critères du formulaire ci-dessus]

English translation

You have asked to visit this site in English. For now, only the interface is translated, but not all the content yet.

If you want to help me in translations, your contribution is welcome. All you need to do is register on the site, and send me a message asking me to add you to the group of translators, which will give you the opportunity to translate the pages you want. A link at the bottom of each translated page indicates that you are the translator, and has a link to your profile.

Thank you in advance.

Document created the 13/09/2004, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/ast-rf-455.html

The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.