0

I'm implementing a kind of JobProcessor that takes long running jobs. These Jobs use information, basically Page, PageField and PageRelation, that define a tree of pages and each page has its own PageFields.

tl;dr How to easily copy a Object structure from Hibernate to use outside a transaction?

More detail:

I use Hibernate to persist these objects, it all works fine. Currently, I run the JobProcessor in a VM where I control the transactions manually:

    this.em.getTransaction().begin();
    job.start();
    this.em.getTransaction().commit();

I sometimes need information on pages, I can retrieve them like so:

    this.em.getTransaction().begin();
    Page page = this.withId(pageId)
    this.em.getTransaction().commit();

Somehow, I got lucky that I never faced LazyInitialization exceptions; I believe because the HibernateSession is never closed.

Now I'm moving to a Spring-controlled environment and try to make all the transactions short and clean. I need the object tree of Page, i.e. all the fields and relations and fields in a long-running method. I think the best way to go is to make a defensive copy of the tree. How can this be easily achieved? Or are there better ways to deal with this problem?

Rob Audenaerde
  • 19,195
  • 10
  • 76
  • 121

1 Answers1

1

So like you said, Hibernate tries to hold off on fetching data until you need it, which is good for performance in general.

Here are a few solutions:

1) If you know you will always need the whole tree of the Page, you can use a Hibernate query with a fetch join to the child entities you need (rather than just doing session.get()). This will force Hibernate to populate the child elements.

2) If it's a situation where you need high level information for each page first, and you only need the rest of the tree when the user takes some action, such as clicking on a particular page, then when the user selects that page, you can use the page id to fetch the child elements for a particular page, probably also using a Hibernate query.

jeff
  • 4,325
  • 16
  • 27