hibernate in action第二版中有一段是这么说明的:
"从获取方法返回一个不同的对象,通常比由Hibernate传递到设置方法的对象来的安全。hibernate按值比较对象--不是按对象的同一性--来确定一个属性的持久化状态是否需要被更新"
下面用代码来说明一下:(比如一个user类)
public class User implements serilizable{
    private String name;    public void setName(String name){
        this.name = name;
    }    //所说建议的写法,这么写就不会导致不必要的sql update
    public String getName(){
        return new String(name);
    }    //而大部分通常的写法是
    public String getName(){
        return this.name;
    }
}
比较迷惑的问题是:
1、如果"对象的同一性"相等的话,那么equals(按值比较)必定相等,这和是否产生不必要的更新有什么因果关系?
2、如果按照他的逻辑,确实可以对性能有少许提升,但是岂不是有点浪费内存了? 

解决方案 »

  1.   

    译文的意思跟原文完全不同了。原文如下:
    It's usually completely safe to return a different object from the getter method to the object passed by Hibernate to the setter.
    正确的翻译应该是:
    从读访问器返回一个与Hibernate传入写访问器的对象不同的对象,这种做法通常是安全的。这里并没有比较两种写法的优劣,更没有推荐使用 return new String(name) 这种写法。在这里写这句话,完全是为后面讨论集合属性持久化状态作铺垫。看书最好看原版,中文版翻译水平普遍不高。
      

  2.   

    感谢楼上两位的解答,分我先结了。
    原文是这样的:
    It’s usually safe to return a different object from the getter method than the
    object passed by Hibernate to the setter. Hibernate compares the objects by
    value—not by object identity—to determine whether the property’s persistent
    state needs to be updated. For example, the following getter method doesn’t
    result in unnecessary SQL UPDATEs:
    public String getFirstname() {
    return new String(firstname);
    }
    后面提到了collection是个例外,必须在getter中严格的返回hibernate 给setter pass的同一个对象。