user1047847
user1047847

Reputation: 11

JPA Lazyness design Advice

I m wondering what is the best way to store within a database a large tree of objects. So far i have the folowing :

@Entity
class Element1 {
    @OneToMany(fetch=FetchType.LAZY)
    Collection<Element2> elements;
    ....
}

The fetch type is set to LAZY beacause Element2 is not always needed and can be really HUGE (collections of collections of collection of other elements).

The problem is when I retrieve an element of type Element2 from a servlet (the session is closed), i get (of course) a lazyness exception. A first solution would be to eager fetch within the query the collection of elements but how do i know when to do it ? Do i have to create to methods :

Element1 get(Integer Id);
Element1 getEager(Integer Id);

I was wondering if i could remove the field elements from Element1 and "reverse" the mapping :

class Element2 {
     @ManyToOne
     Element1 owner;

     .....
}

And then have two methods :

Element1 get(Integer Id);
Collection<Element2> getElements(Element1 owner);

What is the best way to do such things ?

Thank you !!

Upvotes: 1

Views: 90

Answers (1)

JB Nizet
JB Nizet

Reputation: 691735

You can do everything you describe in your question, but the second option is not what I would do. If you need to navigate from element1 to its list of element2, having the OneToMany association is the batural and obvious thing to do. Note that the association can be bidirectional: you can choose to navigate from parent to children, and from child to parent at the same time.

I would go with your first solution: a method that just returns element1, and another method which returns element1 with its children. I would choose more meaningful names for the methods, though.

Upvotes: 1

Related Questions