7

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?

Peter Penzov
  • 7,110
  • 86
  • 300
  • 595
  • Hibernate doesn't like so much when you set the id, are you sure that the object is in the db with specified ID? Try to lookup the object by id and then modify what you need – Federico Paparoni Jul 05 '17 at 20:42
  • When you ask about an exception, always, always post the complete stack trace of the exception. That said, the problem is most probably that you're deleting a row that doesn't exist. – JB Nizet Jul 07 '17 at 19:14
  • 1
    Here is the full stack trace https://pastebin.com/sFGMNGim – Peter Penzov Jul 07 '17 at 20:12
  • My guess is Frederico Paparoni is right. Hibernate use proxy objects and setting IDs doesn't work for exclusions. – Paulo Pedroso Jul 09 '17 at 00:00

2 Answers2

13

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 session before you can manage it with hibernate.

When an object (with generated id) has an id value, hibernate expects that that object exist in his session (because the id value can only exist if hibernate had generated it or hibernate has brought it from the databae 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 databse), 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.

gmanjon
  • 535
  • 3
  • 10
  • 1
    Instead of loading the entire entity just to delete it, you can also create a reference, see https://stackoverflow.com/a/40468433/3080094 – vanOekel Jul 09 '17 at 17:18
  • @GhostCat Didn't even notice, so no worries :) Thanks for the upvote anyway :D – gmanjon Jul 11 '17 at 15:28
  • 1
    @Peter Penzov I would like to add that this behaviour should be the same for other ORM providers as it is documented on the JPA level – Dmitry Senkovich Jul 14 '17 at 09:57
1

The exception is might be happening for the below line

If your object has primary key which is auto generated and you are forcing to assigned key may cause the exception.

Please Visit this page for detail explanation HERE

Suraj Khanra
  • 412
  • 5
  • 22
  • I would venture to say that this is extremely unlikely. The resulting object is only used to request deletion of the underlying database record. The case you are describing is when you want to update or insert a record. – Nathan Jul 14 '17 at 07:50