【问题标题】:hibernate SessionFactory ob休眠SessionFactory ob
【发布时间】:2016-06-28 01:12:10
【问题描述】:

考虑 Hibernate 客户端代码

Configuration cfg = new Configuration();
cfg.configure();

此时持久化类的默认构造函数不会调用。这意味着不会为持久性类创建实例

但在创建 SessionFactory 对象后,即

Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();

默认构造函数会调用 3 次,所以问题是为什么在创建 SessionFactory 对象之后会创建 3 个持久性类对象。

【问题讨论】:

    标签: hibernate configuration sessionfactory


    【解决方案1】:

    这是一个有趣的通知。

    Hibernate 通过加载和检查相应的Class<?> 对象来获取有关映射的所有信息。但是,有时,它需要一个无法从Class<?> 对象获得的信息,例如,调用某个持久化方法的结果。在这种情况下,Hibernate 创建一个持久的临时对象并调用它的方法。

    您可以在默认构造函数上设置断点并检查 Hibernate 实例化持久对象的所有情况。

    我尝试使用 Hibernate 4 和 Hibernate 5 测试这种行为。在这两种情况下,默认构造函数在此方法中仅调用一次,在行中

    final Serializable defaultValue = (Serializable) identifierGetter.get( instantiate( constructor ) );

        /**
         * Return an IdentifierValue for the specified unsaved-value. If none is specified, 
         * guess the unsaved value by instantiating a test instance of the class and
         * reading it's id property, or if that is not possible, using the java default
         * value for the type
         *
         * @param unsavedValue The mapping defined unsaved value
         * @param identifierGetter The getter for the entity identifier attribute
         * @param identifierType The mapping type for the identifier
         * @param constructor The constructor for the entity
         *
         * @return The appropriate IdentifierValue
         */
        public static IdentifierValue getUnsavedIdentifierValue(
                String unsavedValue,
                Getter identifierGetter,
                Type identifierType,
                Constructor constructor) {
            if ( unsavedValue == null ) {
                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 );
                }
                else if ( identifierGetter != null && (identifierType instanceof PrimitiveType) ) {
                    final Serializable defaultValue = ( (PrimitiveType) identifierType ).getDefaultValue();
                    return new IdentifierValue( defaultValue );
                }
                else {
                    return IdentifierValue.NULL;
                }
            }
    
            ...
        }
    

    【讨论】:

    • 是的,这种行为仅适​​用于 Hibernate 3.0。即使有注释,默认构造函数也只调用一次。
    猜你喜欢
    • 2012-01-23
    • 2016-03-21
    • 2013-06-11
    • 2015-06-10
    • 2014-01-10
    • 2012-07-25
    • 2014-06-24
    • 2019-04-13
    • 2013-01-13
    相关资源
    最近更新 更多