我想在一个 @Transaction
方法中将唯一键从一个实体对象更改为另一个实体对象:
Entity oldone=dao.getEntity(oldid);
Entity newone=dao.getEntity(newid);
oldone.setBarcode(null);
dao.update(oldone); //free the unique key "barcode"
newone.setBarcode(barcode);
dao.update(newone); //set the unique key "barcode"
但是此代码会抛出:关键“条形码”的重复条目 调试我发现在第一次 dao.update 之后数据库中没有任何变化。 我尝试将 hibernate 刷新模式设置为“始终”但没有更改:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.bytecode.use_reflection_optimizer">false</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.search.autoregister_listeners">false</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
<prop key="hibernate.flushMode">always</prop>
</props>
</property>
</bean>
为什么 hibernate 不刷新?
最佳答案
看来这个Hibernate属性只是对Hibernate的一个暗示。请参阅here并在 Hibernate ORM Docs ,他们说
Except when you explicitly flush(), there are absolutely no guarantees about when the Session executes the JDBC calls, only the order in which they are executed.
除此之外,FlushMode.ALWAYS enum value Javadoc指出
The Session is flushed before every query. This is almost always unnecessary and inefficient.
我不确定“查询”是否仅意味着数据库询问(读取)或任何类型的操作,包括插入、更新和删除。
如果我是您,我会在第一次更新后显式调用 session.flush()
。我知道声明式方式更干净,但有时命令式编程会让您的业务更安全。
关于java - hibernate 和刷新 : update throws duplicate key error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21399660/