A batch update returned an unexpected row count from update [0];

I use this object to write to the database.

@Entity @Table(name = "SYSTEM_USERS") public class SystemUsersModel implements Serializable { private static final long serialVersionUID = 8432414340180447723L; @Id @GeneratedValue private Integer id; @Column private String username; @Column private String email; @Column @Type(type = "date") @Temporal(TemporalType.DATE) private Date lastlogin; @Column private String password; @Column private String salt; @Column @Type(type = "date") @Temporal(TemporalType.DATE) private Date added; 

Delete request:

 SessionFactory factory = HibernateUtils.getSessionFactory(); Session session = factory.getCurrentSession(); try { session.getTransaction().begin(); SystemUsersModel obj = new SystemUsersModel(); obj.setId(userlist.getId()); session.delete(obj); session.getTransaction().commit(); blacklists.remove(selectedBlackListEntry); selectedBlackListEntry = null; } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } 

Then I run the code, I get this error:

 Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1 

I inserted a few lines using a script before starting the application. How can I solve this problem?

+7
java hibernate
source share
2 answers

When you manage instances of hibernated objects, they must be β€œattached” to the session.

If you create an object with new , you first need to connect it to the session before you can manage it using sleep mode.

When an object (the generated identifier) ​​is id, hibernate expects this object to exist in its session (since the id value can exist only if sleep mode generated it or sleep mode brought it from the database through a request), otherwise case it throws a Stale exception.

You need to either call saveOrUpdate on it for hibernate to create your identifier, and attach an instance to the session (in case it does not exist in the database), or call load with the id for hibernation to bring an instance from the database (if it exists in the database).

In this case, you know the identifier, so you need to request sleep mode to get the attached instance. So try this instead:

 SystemUsersModel obj = session.load(SystemUsersModel.class, userlist.getId()); session.delete(obj); 

Here is an explanation of the different states of the sleeping session instance: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html

Edit : thanks @vanoekel

Or better, you can simply use getReference instead of load , as it will be less expensive in terms of resources if you just want to remove its afterword.

+10
source share

An exception may occur for the next line

If your object has a primary key that is automatically generated and you force the assigned key, this may throw an exception.

Please visit this page for a detailed explanation HERE

+1
source share

All Articles