代码之家  ›  专栏  ›  技术社区  ›  Kms

在Hibernate5.x中加载记录时,默认构造函数被多次执行

  •  0
  • Kms  · 技术社区  · 6 年前

    持久性类

    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;
        }
    }
    

    enter image description here

    原木 Console Logs Screenshot

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

    1 回复  |  直到 6 年前
        1
  •  2
  •   Denis Zavedeev Brian Kelly    6 年前

    第一个电话

    从Hibernate 5.3.7开始 第一 一次发生在 SessionFactory

    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

    UnsavedValueFactory .

    第二个电话

    你在用 Session#load

    proxy类是 @实体

    第二 呼叫

    第三个电话

    Hibernate 初始化实体(调用 getCemail() 冬眠 发布 sql AbstractLazyInitializer#target . 这是 第三的


    为了更好地了解发生了什么,我建议您调试它。

    在默认构造函数处放置一个断点并观察堆栈跟踪。