Friday, 28 December 2012

@JoinTable

I recently had a requirement that I needed to register who is ignoring who on my website.

So, I have a Person class, who can ignore other Persons.

That is a ManyToMany relationship, and thus requires a coupling-table.

In my case, there's the mm_usertable database table and a mm_ignore database table. The mm_ignore table is a classic coupling table in that it has only two fields and both of them are foreign keys to the mm_usertable.

In JPA the @JoinTable annotation is used specifically for these situations.

In case you have more properties that apply to the relationship (i.e. there are more fields in the coupling table) you have no choice but to make a real JPA Entity of the coupling table. For example if you wish to indicate that a relationship has been deleted and/or wish to further describe the relationship, for example family, work, etc.

Good Lord, I mean, there's more annotations here than anything else!

The targetEntity property seems very important, otherwise it won't work. Probably because generic collections are not reified: they are not available at runtime. Generics are implemented using erasure.

No comments:

Post a Comment