0
当我从Domain类调用它时,我想在setter中做一些事情,但是当它从hibernate调用时,我不想做。此外,我使用会话工厂,所以我不能使用@PostLoad触发一个标志!区分从域调用的setter和从休眠中调用的setter
任何机构都有什么想法吗? 谢谢。
当我从Domain类调用它时,我想在setter中做一些事情,但是当它从hibernate调用时,我不想做。此外,我使用会话工厂,所以我不能使用@PostLoad触发一个标志!区分从域调用的setter和从休眠中调用的setter
任何机构都有什么想法吗? 谢谢。
如果您使用注释并注释了字段,那么Hibernate将直接使用反射来访问字段,因此在您的setter中实现自定义逻辑应该没有问题。
如果您使用XML映射,那么你可以指定字段访问:
第5.1.11(https://docs.jboss.org/hibernate/orm/3.5/reference/en/html/mapping.html)
The access attribute allows you to control how Hibernate accesses the property at runtime.
By default, Hibernate will call the property get/set pair. If you specify access="field",
Hibernate will bypass the get/set pair and access the field directly using reflection. Y
ou can specify your own strategy for property access by naming a class that
implements the interface org.hibernate.property.PropertyAccessor.
如果你想确保事遂所愿:
private String name;
public void setName(String name){
if(this.name != null && ! this.name.equals(name){
//do something
}
this.name = name;
}
实际上在setter中实现业务逻辑是一种糟糕的设计实践。尽量让他们只做他们的工作 - 只需设定价值。你为什么需要这种区分? – 2014-12-02 19:27:48
,因为在我看来,二传手的规则是增加更多的逻辑!否则就没有必要,我可以离开这个领域。例如一些其他领域的价值取决于这个领域,并在其变更后,我需要改变其他领域。该领域可以是私人的,没有其他人甚至知道他们存在! – hasan 2014-12-02 19:56:51