代码:
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
User user = new User();
session.delete(user);
当程序执行到最后的delete(user)方法时,出现异常如下:
Hibernate: delete from UserTable where id=?
(impl.SessionImpl 2400) Could not synchronize database state with session
net.sf.hibernate.HibernateException: Batch update row count wrong: 0
at net.sf.hibernate.impl.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:65)
at net.sf.hibernate.impl.BatcherImpl.executeBatch(BatcherImpl.java:128)
at net.sf.hibernate.impl.SessionImpl.executeAll(SessionImpl.java:2438)
at net.sf.hibernate.impl.SessionImpl.execute(SessionImpl.java:2397)
at net.sf.hibernate.impl.SessionImpl.flush(SessionImpl.java:2261)
at net.sf.hibernate.impl.SessionImpl.forceFlush(SessionImpl.java:769)
at net.sf.hibernate.impl.SessionImpl.save(SessionImpl.java:741)
at javamxj.hibernate.Test.main(Test.java:41)
------解决方法--------------------------------------------------------
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
User user = new User(); //实例化对象
session.delete(user);//该对象与表中对应主键为0的row不存在 会抛出异常
------解决方法--------------------------------------------------------
必须要告知删除那条具体数据,改为:
Long id = 1;
User user = (User)sess.load(User.class,id);
session.delete(user);
------解决方法--------------------------------------------------------
应该先加载,后删除,
但是如果你需要直接通过构造的对象删除,
那么你必须给这个对象赋值---主键的值。
----------------------------------------
其实,这最终归结为 hibernate 中 pojo 的三种状态:
1,临时状态
2,持久化状态
3,游离状态,
你要是把这理解了,你的错误的原因你也就知道了!