Hibernate执行查询后又立马执行了更新(default-access)


在项目中遇到利用hibernate执行查询后立马又对数据库数据进行了更新,导致了错误。

public String getName()

    if(this.name==null)
    { 
        this.name=""; 
    } 
    return this.name; 

 
因为在数据库中是null,在hibernate查询时会设置成“”。hibernate会任务session中的实体发生了改变,就会执行update。 
 
解决方式:
 
 采用的解决办法是将配置文件增加一个属性access="field" 这样就不会通过get方法比较属性而直接访问属性字段
 <property name="name" type="java.lang.String" access="field">
  <column name="name" length="20" />
  </property> 
 
default-access="field ¦property ¦ClassName"   

这里field表示Hibernate直接读取类中的字段值。
 这种方式如果你在业务中不需要getter和setter的话,就可以不用写了。 这时,可以设置属性为不可变,可以不用执行脏检查。
 
property(默认)表示Hibernate通过getter和setter读取。
 这种方式可以在getter和setter中做额外的处理。
 
ClassName,是指使用实现了org.hibernate.property.PropertyAccessor接口的类的具体策略来访问字段属性。

相关内容