user2035039
user2035039

Reputation: 971

Why do I get a StaleObjectStateException on removing entity?

In my Spring Boot web app, I have a controller, which provides a method to remove an entity from the database, which in turn calls a DAO class. However, when I call entityManager.remove(entity), I receive a StaleObjectStateException, even though entity was just retrieved from the database and there was no other call to my API which may have altered entity.

This is my controller:

@Transactional
@RestController
public class AppAdminController {
    ...
    @RequestMapping(value = "/admins/{username}", method = RequestMethod.DELETE)
    public void deleteAdmin(@PathVariable("username") String username) {
        dao.removeByUsername(username);
  }
}

DAO:

@Service
public class AppAdminDao extends AbstractDAO<UUID, AppAdmin> {

    public AppAdmin getByUsername(String username) {
        TypedQuery<AppAdmin> query = em.createQuery("SELECT a FROM AppAdmin a WHERE a.username=:username", AppAdmin.class);
        query.setParameter("username", username);

        try {
            return query.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    public void removeByUsername(String username) {
        AppAdmin admin = getByUsername(username);
        if(admin != null) {
              em.remove(admin);
        }
    }
}

An AppAdmin aa is added by calling

AppAdmin res = em.merge(aa);

and even calling em.remove(res) immediately after adding the entity yields the exception mentioned above. What am I doing wrong?

Upvotes: 2

Views: 4608

Answers (1)

user2035039
user2035039

Reputation: 971

Following the hint of PaulNUK, I added an @Version annotated field to my entity. Now I received the following exception on adding an entity to my database: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1.

The problem turned out to be the following: My entity has a UUID as an id, which was annotated as follows:

@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")

Adding

@Column(columnDefinition = "BINARY(16)")

solved the problem.

Upvotes: 5

Related Questions