试图在Hibernate 5.x中加载记录时,默认构造函数被执行很多次 [英] Default constructor getting executed many times when tried to load records in Hibernate 5.x

查看:40
本文介绍了试图在Hibernate 5.x中加载记录时,默认构造函数被执行很多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我理解一下,为什么尝试在Hibernate 5.x中加载记录时默认构造函数会多次执行

Could some one please help me to understand, Why default constructor getting executed many times when tried to load records in Hibernate 5.x

持久性类

public class Customer {

    private int cid;
    private String cphone;
    private String ccity;
    private String cemail;

    public Customer() {
        System.out.println("**Default Constructor**");
    }

    public Customer(String cphone, String ccity, String cemail) {
        this.cphone = cphone;
        this.ccity = ccity;
        this.cemail = cemail;
    }

    public int getCid() {
        return cid;
    }

    public void setCid(int cid) {
        this.cid = cid;
    }

    public String getCphone() {
        return cphone;
    }

    public void setCphone(String cphone) {
        this.cphone = cphone;
    }

    public String getCcity() {
        return ccity;
    }

    public void setCcity(String ccity) {
        this.ccity = ccity;
    }

    public String getCemail() {
        return cemail;
    }

    public void setCemail(String cemail) {
        this.cemail = cemail;
    }
}

加载记录的步骤

日志

注意:已尝试使用SQLServer 2014和Hibernate 5.3.7

Note: Tried with SQLServer 2014 and Hibernate 5.3.7

推荐答案

第一个呼叫

从Hibernate 5.3.7开始,第一个发生在 SessionFactory 初始化过程中:

The first call

As of Hibernate 5.3.7 the first one happens during SessionFactory initialization process:

if ( identifierGetter != null && constructor != null ) {
    // use the id value of a newly instantiated instance as the unsaved-value
    final Serializable defaultValue = (Serializable) identifierGetter.get( instantiate( constructor ) );
    return new IdentifierValue( defaultValue );
}

似乎可以弄清楚 @Id 字段的哪个值表示 @Entity 未保存.

Seems it figures out which value of the @Id field indicates that an @Entity is unsaved.

请参见您正在使用

You're using Session#load, which returns a proxy for the entity assuming it exists.

代理类是 @Entity

因此,代理类的构造函数调用了超级构造函数.因此,第二呼叫

So the proxy class' constructor calls super constructor. Hence the second call

然后,您将强制 Hibernate 初始化实体(您调用 getCemail()). Hibernate 发出 sql 语句,然后初始化

Then you're forcing Hibernate to initialize the entity (you call getCemail()). Hibernate issues the sql statement and then initializes AbstractLazyInitializer#target. This is the third call to the constructor

为了更好地了解发生了什么,我建议您对其进行调试.

To better understand what is going on I would recommend you to debug it.

在默认构造函数上放置一个断点,并查看堆栈跟踪.

Put a breakpoint at the default constructor and watch the stack trace.

这篇关于试图在Hibernate 5.x中加载记录时,默认构造函数被执行很多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆