8

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...
Floaz
  • 140
  • 1
  • 5
  • I created a new project from scratch with fruits as classes. And i had the same problem. Either I did not understand the use, or it is actually an error. – Floaz Feb 23 '13 at 22:15
  • Do u resolve this issue? – Andrew Kalashnikov Feb 27 '13 at 16:23
  • I could not solve the problem! Sorry! I have no time for solving it, but next month i'll try it again. – Floaz Mar 15 '13 at 17:33
  • This has to be a bug. Someone should report this. – Bat0u89 Aug 15 '13 at 12:07
  • Did you have a look at http://stackoverflow.com/questions/17300157/are-there-other-use-cases-for-polymorphismtype-explicit-than-the-lightweight-p and the questions linked from there? – xwoker Aug 19 '13 at 10:52
  • In Hibernate 3.2 I use Polymorphism explicit on the base class and works. Peraphs is a bug of Hibernate 4! Oh my god! – Joe Taras Aug 21 '13 at 22:08

2 Answers2

4

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.!!

Dileep
  • 5,362
  • 3
  • 22
  • 38
1

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.

xwoker
  • 3,105
  • 1
  • 30
  • 42