I’m working in a project that’s already grown up, so I won’t be able change any version of any of the used frameworks or libraries.
Actually, I had a particular situation that I managed to resolve with two entities and @Inheritance, @DiscriminatorColumn and @DiscriminatorValue. Now, I have an entity with references to both classes in the inheritance, like this:
@Entity
//Other annotations
public class A implements IA {
//Class body
}
@Entity
//Other annotations
public class B extends A implements IB { //Note: `IB` extends `IA`.
//Class body
}
@Entity
//Other annotations
public class Container {
private IA object1;
private IA object2;
}
The problem here is that I’m trying to use @Any annotation, because either object1 and/or object2 can be of type A or B. What I’ve done is this:
@Any(metaColumn=@Column(name="objectOneType", length=3),fetch=FetchType.EAGER)
@AnyMetaDef(idType="long",metaType="string", metaValues={
@MetaValue(targetEntity=A.class, value="A"),
@MetaValue(targetEntity=B.class, value="B")
}
)
@JoinColumn(name = "relatedObjectId")
private IA object1;
As stated here, Hibernate’s @Any annotation family has no counterpart in JPA 2 and, since I can’t switch to Hibernate 4.1, I’m stuck here trying to figure out a way to make it work or what should I do to fix it.
A “not so elegant” way would be to create a new entity and copy the fields from A to B, erasing the inheritance and fixgin the particular cases.
Maybe, I’m losing some particular feature in JPA that I don’t know yet, so I’m currently open to and thank any kind suggestion that might point me in the right direction.
You don’t need any
@Anyannotation. B extends A, so Bisan A. So the following is sufficient:(assuming the association is a ManyToOne. It could also be a OneToOne)
Hibernate will figure out the concrete type of both objects all by itself, and will initialize object1 and object2 with an instance of A or B.