File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Object Relational Mapping and the fly likes A sense of style: @OneToMany or @ElementCollection? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "A sense of style: @OneToMany or @ElementCollection?" Watch "A sense of style: @OneToMany or @ElementCollection?" New topic

A sense of style: @OneToMany or @ElementCollection?

Marcos APS

Joined: Mar 09, 2009
Posts: 5
Hello, everybody!

First of all, I would like to say that I already posted this question in other forums:

but as I haven't got any answer from there I'm posting it here too in the hope that I find one, as this is very important to me. This forum is my last hope.

In JPA 1.0 I could map the collection association to DocumentSubject (only accessible through the Document entity) like this:

In JPA 2.0 I can get rid of the DocumentSubjectId class, transform DocumentSubject in an @Embeddable and use the @ElementCollection annotation, like this:

So, my question is: what is the recommended to use in this case: relationships to entity classes, like in the first case, or collection of embedded classes, like the second case? Note that I will never access in my application the DocumentSubject separately from the Document class. It really belongs to the Document class. What would you use in JPA 2.0, and why?

Thank you in advance.

James Sutherland
Ranch Hand

Joined: Oct 01, 2007
Posts: 553
Which to use is entirely up to you. I would normally recommend using the OneToMany, as typically even if a class starts out as embeddable, you eventually find that you would like to query and edit it independently.

Embeddables have a bunch of restrictions on them that Entitys do not (can't query directly, can't persist/merge/remove directly, JPA does not currently define inheritance, relationships restrictions).

Using an ElementCollection is much simpler however, so it does have its benefits, especially when prototyping.

TopLink : EclipseLink : Book:Java Persistence : Blog:Java Persistence Performance
Marcos APS

Joined: Mar 09, 2009
Posts: 5
Thank you, James, I think I will stick with @OneToMany for now.

I agree. Here's the link:
subject: A sense of style: @OneToMany or @ElementCollection?
It's not a secret anymore!