14

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

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

谢谢!

4

5 回答 5

10

这是可行的:

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

/**
 * 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;
于 2010-11-03T22:54:56.327 回答
3

Take a look at UserType. You'd need to call your factory in nullSafeGet() and populate all the fields yourself though. Reverse work is done in nullSafeSet().

于 2009-06-05T02:21:19.310 回答
2

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

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

于 2009-06-08T02:40:14.910 回答
0

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

于 2009-06-05T01:06:27.810 回答
0

我不知道我是否完全理解您的要求,但我认为这里描述了一个解决方案(参见解决方案 4 - Hibernate 拦截器,方法 onLoad):“Domain Driven Design with Spring and Hibernate” http:// www.jblewitt.com/blog/?p=129

于 2010-11-13T11:10:28.553 回答