Hibernate不会抛出StaleObjectStateException(不要做OPTIMISTIC LOCKING)

时间:2012-12-08 01:42:24

标签: spring hibernate

我很困惑。我想在我的spring hibernate程序中实现乐观锁定,但是即使我在单独的浏览器中打开数据并单独更新它,hibernate也没有抛出StaleObjectStateException。

我的Dao看起来像这样:

public void update(User user) throws StaleObjectStateException{       
sessionFactory.getCurrentSession().saveOrUpdate(user);
}

我的Pojo看起来像这样:

@Version@Temporal(TemporalType.TIMESTAMP)
@Column(name="timestamp", length=19)
public Timestamp getTimestamp() {
return this.timestamp;
}

的Config.xml

<bean name="sessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation">
        <value>classpath:hibernate.cfg.xml</value>
    </property>
    <property name="configurationClass">
        <value>org.hibernate.cfg.AnnotationConfiguration</value>
    </property>
</bean>
<tx:annotation-driven />
<bean name="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

我怀疑它为什么不抛出异常是因为在更新时,其他会话时间戳也会更新,因为数据是持久的?请帮忙。

佩里

1 个答案:

答案 0 :(得分:0)

我看到你正在使用spring transaction manager。所以我想某处你有@Transactional注释跟踪你的交易。在这种情况下,我认为StaleObjectStateException将不会抛出您的类的更新方法,而是在提交事务时。我还认为spring会将hibernate异常包装到HibernateOptimisticLockingFailureException中。因此,您需要将throws声明添加到标有@Transactional注释的方法中。 如果您没有任何事务性注释,则需要在Dao中添加一些或使用手动事务处理。

相关问题