问题
I am facing problem with hibernate's explicit polymorphism. I used the polymorphism annotation and set it to explicit, but with get() and collections in mapped classes i always get all subclasses. I see all subclasses with left join in the hibernate "show_sql" output. What's the problem? Do I understand the documentation wrong? Or is it a bug in hibernate 4? I haven't seen any example with hibernate 4 and polymorphism annotation.
sessionFactory.getCurrentSession().get(Node.class, 111); // return subclasses!
@Entity
@Table(name="Nodes")
@Inheritance(strategy = InheritanceType.JOINED)
@Polymorphism(type= PolymorphismType.EXPLICIT)
public class Node implements Serializable {
...
}
@Entity
@Table(name="Persons")
public class Person extends Node {
}
@Entity
@Table(name="Networks")
public class Network extends Node {
}
...and other subclasses...
回答1:
Its a common miss understanding, I too had the same doubt once..
This is what really Happens in explicit polymorphism .
polymorphism explicit only applies on root entities and prevent queries naming a (unmapped) superclass to return mapped sub entities
In your case, if Entity Class Nodes were not mapped and Persons were having polymorphism explicit, then Nodes would not return Persons elements.
Look at this code..
@Entity
@Table(name="Nodes")
@Inheritance(strategy = InheritanceType.JOINED)
public class Node implements Serializable {
...
}
@Entity
@Polymorphism(type= PolymorphismType.EXPLICIT)
@Table(name="Persons")
public class Person extends Node {
}
@Entity
@Polymorphism(type= PolymorphismType.EXPLICIT)
@Table(name="Networks")
public class Network extends Node {
}
Its basically the reverse of what everyone have in there mind.!!
回答2:
If you look at the definition of PolymorphismType.EXPLICIT it says:
EXPLICIT: This entity is retrieved only if explicitly asked.
To hide the subclasses, you will have to annotate the subclasses with EXPLICIT and not the base class.
来源:https://stackoverflow.com/questions/14571629/hibernate-4-explicit-polymorphism-annotation-not-working