Lazy/Eager loading strategies in remoting cases (JPA)

后端 未结 3 1213
予麋鹿
予麋鹿 2020-12-05 05:47

I\'m running into LazyLoading exceptions like the most people who try remoting with an ORM. In most cases switching to eager fetching solves the problem (Lazy Loading / Non

相关标签:
3条回答
  • 2020-12-05 06:31

    Although it takes a bit of work and for JAX-WS/JAXB requires recent versions of those libraries, this is a very elegant solution: create a marshaller that can test for whether objects / collections have been initialized.

    As described here: https://forum.hibernate.org/viewtopic.php?f=1&t=998896

    0 讨论(0)
  • 2020-12-05 06:51
    1. You can get rid of all collections whatsoever and use NamedQueries instead. We used this approach in one project (EJB + Swing), and it worked pretty well - thus you determine exact data to be fetched. NamedQueries are normal queries, imagine them as PreparedStatement-s. The idea is not to create/retreive/update/delete single objects with queries. The idea is that you fetch your Collections with queries. For example, instead of mapping a @ManyToMany List, define a NamedQuery that fetches that list. Thus you can fetch the collection data separately, and only whenever you need it, not automatically.

    2. Use a custom Proxy (using CGLIB) for transferred objects - whenever a collection is referenced (via its getter), attempt retreival, and catch any LazyInitializationException and make a call to the server tier for the data requested.

    3. Just as the previous one, but make proxies only of the collections, in the way Hibernate proxies them when lazy initialization is needed.

    4. Also, take a look at the Value List Handler pattern - might be useful.

    (You can also use hibernate.max_fetch_depth (if using Hibernate) with a combination of the above, if it is suitable for your case.)

    0 讨论(0)
  • 2020-12-05 06:53

    Nowadays (2013), it is possible to keep lazy-loading if you remote your service with GraniteDS.

    That should properly serialize your JPA or Hibernate entities by not initializing lazy relations and keeping the lazy-state for the client. If you access those relations on the client, it will fetch them transparently in the background.

    Moreover, GraniteDS seems to be able to do inverse lazy loading which means that when you send modified objects back to the server, it will not send unchanged entities back thus making the necessary server communication very efficient.

    I am not a GraniteDS expert (yet) but it seems to be able to integrate with JEE6 and Spring service layers and works with all of the most important JPA providers.

    Naturally, you will need to hide the GraniteDS based remoting behind a service interface for maximizing transparent behaviour but that can be easily be done if the client also uses Spring (so you inject the service according to the needs of the environment).

    0 讨论(0)
提交回复
热议问题