I use this entity in order to record into 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 query:
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 had inserted several rows using script before I start the application. How I can solve this issue?
When you manage instances of objects with hibernate, they have to be "attached" to the session.
If you create an object with new
you need first to attach it to the session before you can manage it with hibernate.
When an object (with generated id) has an id value, hibernate expects that the object exist in his session (because the id value can only exist if hibernate had generated it or hibernate has brought it from the database via a query), otherwise it throws the Stale Exception.
You have to either call saveOrUpdate
on it for hibernate to create its Id and attach the instance to the session (in case it doesn't exist in the database), or call load
with the id for hibernate to bring the instance from the database (in case it exists in the database).
In this case you know the id, so you have to query hibernate to obtain an attached instance. So, try this instead:
SystemUsersModel obj = session.load(SystemUsersModel.class, userlist.getId());
session.delete(obj);
Here is the explanation of the different states of an instance respect of the hibernate session: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html
Edit: Thanks to @vanoekel
Or better, instead of load
you can just use getReference
as it will be less expensive in terms of resources, if you just want to delete it afterwords.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With