Reputation: 193
I am trying to print in console the names of the fields of a superClass i needed for a later computing is working OK when is a simple POJO but when the class is previously loaded by Hibernate i am getting the fields of the child not the superClass and when i print the name of the parent (when loaded by Hibernate i am getting the following)
[handler,_filter_signature,serialVersionUID,methods]
here is my code
public static void main(String[] args)
{
FixingModels clazz = new FixingModels();
HibernateHandler handler = new HibernateHandler(true);
Student student = (Student)handler.getSession().load(Student.class,1);
Student newStudent = new Student();
System.out.println("Printing Class loaded by Hibernate");
clazz.showFieldsFromSuperClass(student);//show the Fields of the Child and parent wrong
System.out.println("--------------------------------------------------");
System.out.println("Printing Class instance by new..");
clazz.showFieldsFromSuperClass(newStudent);//Show the fields from the parent and child IS O.K
}
private void showFieldsFromSuperClass(Student clazz)
{
final Class objectClass = clazz.getClass();
final Class parentClass = objectClass.getSuperclass();
System.out.println("Printing Child");
for(Field field:objectClass.getDeclaredFields())System.out.println(field.getName());//printing child
System.out.println("Printing Parent");
for(Field field:parentClass.getDeclaredFields())System.out.println(field.getName());//printing parent
}
the first time
clazz.showFieldsFromSuperClass(student);
is called is printing [handler,_filter_signature,serialVersionUID,methods] later the the fields from the child is like the hibernate is now the parent of my student class not my abstract class in code. later
clazz.showFieldsFromSuperClass(newStudent);
is printing the right fields the student fields as well it's parent Person in this case
my question is how can i get the Person class fields[Parent Class] whenever comes from new instance of by hibernate or by Spring container??
Upvotes: 1
Views: 419
Reputation: 15240
Hibernate load() method doesn't fully initialize the retrieved object, but returns a proxy until you access an object property.
You can get the correct Class
of the object without initializing it using a special hibernate helper class:
HibernateProxyHelper.getClassWithoutInitializingProxy(student);
Upvotes: 1
Reputation: 1500845
Basically I suspect Hibernate is creating another subclass of your "child class" on the fly - and creating an instance of that when you fetch it from the session. Your code is currently relying on the instance being a direct instance of just Student
.
This is easy to verify:
System.out.println("Instance class: " + objectClass);
I suspect what it prints is not what you're expecting to see.
Given that you know the parent class you want (the superclass of Student
, presumably) why not just refer to that explicitly using a class literal?
Upvotes: 1