org.hibernate.StaleStateException: Batch update returned unexpected row count fr

本文详细解析了在使用Hibernate框架时遇到的StaleStateException异常的原因及解决方案。异常源于页面赋值过程中将字典对象ID错误地赋给了目标对象,导致数据库更新时预期行数与实际行数不符。通过修正隐藏字段的值,确保正确引用对象ID,从而解决了该问题。

org.hibernate.StaleStateException: Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

 

原因:经debug,发现更新对象的id在数据库中实际库中的id不对应

       

         原来是在页面中对对象id的附值过程中  把对象中字典对象的id附给了它,附错了

 

 

 

<input type="hidden" name="developThirds[<s:property value='#fn.index'/>].id" value="<s:property value='#developThird.sysDictionary.id'/>"/>

 

 

正确的应该如下:

<input type="hidden" name="developThirds[<s:property value='#fn.index'/>].id" value="<s:property value='#developThird.id'/>"/>

 

区别 value="<s:property value='#developThird.sysDictionary.id'/>" 和  value="<s:property value='#developThird.id'/>"/

解决Hibernate执行批量操作时出现 `StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1` 异常,可参考以下方法: - **检查 `@GeneratedValue` 注解**:若使用MySQL数据库且实体类用注解配置,需查看实体类代码。若MySQL里ID已设为自动增长,而实体类又用 `@GeneratedValue` 注解设置,可能导致数据库操作失败。此时把 `@GeneratedValue` 注释掉,问题可能解决[^2]。 - **检查对象ID赋值**:使用 `hibernate` 的 `ht.saveOrUpdateAll(entityList)` 方法时,若报错,需调试查看对象。若把对象的ID设置成其他对象的ID,会导致该异常,需确保对象ID赋值正确[^3]。 ```java // 示例代码,确保对象ID赋值正确 import java.util.ArrayList; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; // 假设这是实体类 class Entity { private Integer id; // 其他属性和getter、setter方法 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } public class Main { public static void main(String[] args) { Configuration configuration = new Configuration().configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); List<Entity> entityList = new ArrayList<>(); Entity entity1 = new Entity(); // 确保ID赋值正确 entity1.setId(1); entityList.add(entity1); try { session.saveOrUpdateAll(entityList); transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } finally { session.close(); } } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值