Bidirectional Association with @ElementCollection

Have you ever wondered, how to map a bidirectional association from an entity to the instances of its element-collection? Actually, it is very easy, if you are using hibernate. It is just somehow hard to find in the documentation, if you are searching for it (look for chapter 2.4.3.4 in the Hibernate-Annotationss-Documentation).

Hibernate

So, here we go: Just add the @Parent-annotation to the attribute of your associated @Embeddable-class, that points back to its parent.

@Entity
class Cat
{
  @Id
  Long id;

  @ElementCollection
  Set kittens;

  ...
}

@Embeddable
class Kitten
{
  // Embeddable's have no ID-property!

  @Parent
  private Cat mother;

  ...
}

Drawback

But this clean approach has a drawback: it only works with hibernate. If you work with other JPA-implementations or plain old JPA itself, it will not work. Hence, it will not work in googles appengine, for example!

Unfortunatly, there are no clean workarounds, to get bidirectional associations to @ElementCollections‘s working with JPA. The only workarounds I found, only work for directly embedded instances – not for collections of embedded instances:

If you want bidirectiona associations to the elements of your embedded collection, it works only with hibernate!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>