我可以让Hibernate通过工厂方法创建一个对象吗?

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

如果无法映射,Hibernate是否会逐个类地为自定义对象创建提供钩子?

谢谢!

这是可行的使用:

  • 自定义EntityPersister实现(您可以在使用自定义Configuration Hibernate初始化期间注册特定实体 )〜或〜
  • 实现Interceptor.instantiate()方法的自定义Interceptor

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

 /** * Instantiate the entity class. Return null 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 null to choose default behaviour */ public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException; 

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

如果无法映射,Hibernate是否会逐个类地为自定义对象创建提供钩子?

检查实体监听器。 这些只会添加可以帮助您的注释。 想想@PrePersist或@PostLoad。

请参阅Hibernate和Spring事务 – 使用私有构造函数/静态工厂方法 ,但不是避免“reflection设置属性或字段”部分的解决方案。

我不知道我是否完全理解你要求的内容,但我认为这里描述了一个解决方案(参见解决方案4 – Hibernate拦截器,方法onLoad):“Spring驱动设计与Spring和Hibernate” http:// http://www.jblewitt.com/blog/?p=129