java - hibernate 和刷新 : update throws duplicate key error

标签 java mysql hibernate flush

我想在一个 @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/

相关文章:

java - AsyncTask 进度条

java - 模型驱动接口(interface)是否会在 struts2 中构成安全漏洞?

mysql - "Client does not support authentication protocol"- 错误已修复,但会导致管理员出错

java - 为 PostgreSQL 使用种子文件时 JPA 中的异常

java - 在 JPanel 周围移动 JTextArea

java - 正则表达式在字符类中指定计数器

php - 读取excel文件并将其存储到mysql数据库

php - Mysql 限制选择不共享列的行

java - Gradle通过不同的注释处理器两次生成Querydsl元数据

hibernate - 如何在 Grails 中暂时禁用只读二级缓存 hibernate 策略?