繁体   English   中英

Java反射超类由休眠问题加载

[英]Java reflection superClass loaded by hibernate problems

我正在尝试在控制台中打印我稍后用于计算的超类​​的字段名称,当它是一个简单的POJO时,可以正常工作,但是当该类先前由Hibernate加载时,我正在获取子级的字段,而不是超类,当我打印父母的名字时(由Hibernate加载时,我得到以下信息)

[handler,_filter_signature,serialVersionUID, 方法 ]

这是我的代码

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
}

第一次

clazz.showFieldsFromSuperClass(student);

被称为是印刷[处理程序,_filter_signature,serialVersionUID的, 方法 ]后来从孩子的领域就像休眠现在是我的学生班不是我的代码抽象类的父。 后来

clazz.showFieldsFromSuperClass(newStudent);

在这种情况下,也正在打印学生字段的正确字段及其父对象

我的问题是,无论何时来自休眠或Spring容器的新实例,如何获取Person类字段[Parent Class]?

基本上,我怀疑Hibernate正在动态创建“子类”的另一个子类-并在从会话中获取它时创建该子类的实例。 您的代码当前依赖于该实例是仅仅是 Student直接实例。

这很容易验证:

System.out.println("Instance class: " + objectClass);

我怀疑它所打印的不是您期望看到的。

既然您知道想要的父类(大概是Student的超类),为什么不只使用类文字显式地引用它呢?

Hibernate load()方法不会完全初始化检索到的对象,但是会返回一个代理,直到您访问对象属性为止。

您无需使用特殊的休眠帮助器类即可获得对象的正确Class ,而无需对其进行初始化:

HibernateProxyHelper.getClassWithoutInitializingProxy(student);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM