【问题标题】:Can I have Hibernate create an object through factory method?我可以让 Hibernate 通过工厂方法创建一个对象吗?
【发布时间】:2009-06-05 00:48:47
【问题描述】:

有没有办法在 Hibernate 中映射工厂方法(而不是让 Hibernate 调用默认构造函数并反射设置属性或字段)?

如果它不能被映射,Hibernate 是否提供了一个钩子来逐个类地创建自定义对象?

谢谢!

【问题讨论】:

    标签: java hibernate orm factory


    【解决方案1】:

    这是可行的:

    我认为拦截器方法更容易。这是Interceptor.instantiate()的javadoc:

    /**
     * Instantiate the entity class. Return <tt>null</tt> to indicate that Hibernate should use
     * the default constructor of the class. The identifier property of the returned instance
     * should be initialized with the given identifier.
     *
     * @param entityName the name of the entity
     * @param entityMode The type of entity instance to be returned.
     * @param id the identifier of the new instance
     * @return an instance of the class, or <tt>null</tt> to choose default behaviour
     */
    public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException;
    

    【讨论】:

    • 这些解决方案都没有解决问题的“反射设置属性或字段”部分。
    【解决方案2】:

    Take a lookUserType。您需要在 nullSafeGet() 中调用您的工厂并自己填充所有字段。反向工作在 nullSafeSet() 中完成。

    【讨论】:

      【解决方案3】:

      如果它不能被映射,会 Hibernate 提供了一个自定义钩子 逐类创建对象 依据?

      查看实体侦听器。这些仅添加了可以帮助您的注释。想想@PrePersist 或@PostLoad。

      【讨论】:

        【解决方案4】:

        请参阅Hibernate and Spring transactions - using private constructors/static factory methods,但不是避免“反射设置属性或字段”部分的解决方案。

        【讨论】:

          【解决方案5】:

          我不知道我是否完全理解您的要求,但我认为这里描述了一个解决方案(参见解决方案 4 - Hibernate 拦截器,方法 onLoad):“使用 Spring 和 Hibernate 进行域驱动设计”@ 987654321@

          【讨论】:

          • 不,onLoad 不允许改变 Hibernate 实例化实体的方式,这就是问题所在。
          • 我以为问题是在问如何填充这些对象,据我所知,Interceptor.instantiate 没有得到任何参数值,只有类名和对象 id
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-03-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-24
          • 1970-01-01
          • 2011-07-24
          相关资源
          最近更新 更多