Graham
Graham

Reputation: 4295

How does JPA's @OneToMany know the Generic entity type at runtime

According to the JavaDoc on @OneToMany, you don't need to specify targetEntity if the "collection property is defined using Java generics". On top of this, you don't need to instantiate the collection property at construction time, but can leave it as null. For example:

@OneToMany(mappedBy="student")
private Collection<Qualification> qualification;

However, as I understood Generics and Type Erasure, at runtime all it's possible to see is that this is a Collection and not a Collection of Qualification - because as I understood it the generic type has been erased here already.

How does this work? What am I missing?

Upvotes: 1

Views: 1016

Answers (2)

Christian Kuetbach
Christian Kuetbach

Reputation: 16060

You missing the conter-part of this annotation:

With mappedBy="student" you defined the possible Classes, because you are "linking" to another database table. And that table has a Java-Binding, too. So JPA will try to create an Object from the N-table and add them into the list.

update

In JPA, there is something called @DiscriminatorColumn, if you setup a table for all inherited classes. You also can specify one table per conreete class.

http://en.wikibooks.org/wiki/Java_Persistence/Inheritance

Upvotes: 0

Graham
Graham

Reputation: 4295

Thanks to Thomas W for pointing this out. You can get the Generic type information from Methods and Fields on a class using reflection, using Method.getGenericReturnType() and Field.getGenericType(), which will then give enough information to know what's needed to do here.

Upvotes: 2

Related Questions