views:

28

answers:

1

Lets say I retrieve an entity object that looks like this:

@Entity
public class Mother {
    ...

    @OneToMany(mappedBy = "mother",
               targetEntity = Child.class,
               fetch = FetchType.LAZY)
    public List<Child> getChildren() {
        return children;
    }
}

When retrieving the above object, I commit the transaction (and close the session associated with the object). Later on in the code, there is a need to retrieve the children. If I wanted to keep the fetch type as LAZY, is there a way to use the Mother object and still be able to call getChildren() to retrieve the children? Or would I have to just bite the bullet and query the children via the key of the Mother?

+1  A: 

If I wanted to keep the fetch type as LAZY, is there a way to use the Mother object and still be able to call getChildren() to retrieve the children?

Not if the EntityManager has been closed.

Or would I have to just bite the bullet and query the children via the key of the Mother?

You could retrieve the children when getting the mother using a FETCH JOIN:

SELECT m
FROM Mother m LEFT JOIN FETCH m.children
WHERE m.id = :id

Other options include:

  • using the Open Entity Manager in View pattern (if you are using a webapp)
  • using an extended persistence context.
Pascal Thivent
This 'problem' makes me put a lot of getChildrenFor(Mother m) in my service layer. Feels wrong, but not sure what to do.
willcodejavaforfood
@willcodejavaforfood: Well, it depends on your use case and the design of your app but if you're just adding them to avoid lazy loading problems, you're kinda polluting your business layer.
Pascal Thivent
Thought so. It's when I need to display it in my GUI (Swing) normally and I don't want to create a transaction in my view model. Maybe I should? :)
willcodejavaforfood
The FETCH JOIN solution is if you expect to always want to retrieve the children of the mother right? I guess my problem is that if a commit is called and then later there might be an if-statement and 'then' you decide you need to retrieve the children. I guess then you would just have to query the children in a new transaction anyway.
digiarnie
@digiarnie It all depends on your "business flow" and I can't be more precise without more details. But yes, a fetch join is useful is you *know* you'll need the association.
Pascal Thivent