Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate 4 explicit polymorphism (annotation) not working?

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...
like image 608
Floaz Avatar asked Jan 28 '13 21:01

Floaz


2 Answers

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

like image 79
Dileep Avatar answered Oct 29 '22 02:10

Dileep


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.

like image 1
xwoker Avatar answered Oct 29 '22 03:10

xwoker