Reputation: 2657
I am using JPA discriminators to obtain specific sub classes as follows (class names changed for simplicity)
@Entity
@Table(name="TYPE")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="SUB_TYPE", discriminatorType=DiscriminatorType.INTEGER)
public class Type {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="TID")
private Foo foo;
}
@Entity
@DiscriminatorValue("1")
public class Type1 extends Type {
//Type1 stuff
}
//Other Type subclasses
As you can see "Type" class is in a many-to-one relationship with the Foo class, however in generics as Set<Type1>
is not a subtype of Set<Type>
we cannot just speicify the 'inverse' relationship in Foo as Set<Type> types;
Therefore my Foo class uses wildcards but also ensures that only subclasses of Type can be set as types as follows;
@Entity
@Table(name="FOO")
public class Foo {
//bi-directional one-to-many association to Type
@OneToMany(mappedBy="foo")
Set<?> types;
public Set<?> getTypes() {
return types;
}
public void setTypes(Set<? extends Type> types) {
this.types = types;
}
}
The question is - how do I explicitly tell JPA that the Set should be of type 'Type'? If this is not possible, what are my alternatives to setting this inverse relationship, while still using discriminators?
Upvotes: 1
Views: 388
Reputation: 21145
The OneToMany annotation can specify the targetEntity:
@OneToMany(mappedBy="foo", targetEntity = Type.class)
Set<?> types;
This is optional when generics can be used to define the type, but required in your situation.
http://docs.oracle.com/javaee/6/api/javax/persistence/OneToMany.html
Upvotes: 1