Consider the following example:
public interface Bar {
}
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public DefaultBar implements Bar {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private long id;
}
@Entity
public class Foo {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private long id;
@OneToMany(cascade = CascadeType.ALL, targetEntity = DefaultBar.class)
@JoinColumn(name = "FOO_ID")
private Collection<Bar> bars;
public Collection<Bar> getBars() {
return bars;
}
}
That’ll work all right. BUT – suppose I’ll make a subclass of Foo; say FooFoo. And I want the “bars” association to point to a new implementation of Bar too. Say:
@Entity
public NewBar extends DefaultBar {
}
And now I would like to annotate FooFoo so it sets the target entity of the “bars” field to the NewBar class.
@Entity
@AssociationOverride(name="bars", ???????)
public class FooFoo extends Foo {
}
I noticed the annotation @AssociationOverride, but at first sight it doesn’t allow the target entity to be overriden. Or does it ?
There seems to be no way to do this in context of JPA. Hibernate has specific meta-annotations to override a OneToMany annotation of a superclass.
In the meantime it appears the @AssociationOverride annotation only applies to classes marked with @MappedSuperclass. But then they can’t be used as target entity in the OneToMany association.
Chicken and egg problem really… Or is it ?
Java does not allow the override of fields. But it does for methods. If the superclass uses property access, THEN is works. Let the subclass override the getter and there you go ! 🙂