javaspringspring-bootspring-data-jpacrud

Spring Boot JPARepository .save() method inserts a new row when updating an enum attribute


I'm working with Spring Boot 3 and using JPARepository to manage my database operations. I've encountered an unexpected behavior when attempting to update an entity's enum attribute.

Scenario:

I fetch an existing Book entity:

Book book = bookDao.findById(...);

I update the title and an enum attribute (Type):

book.setTitle("Book1");
book.setType(Type.DRAMA);  // Enum field
bookDao.save(book);

Issue: Upon executing the above, instead of updating the existing record, a new Book object is inserted into the database.

However: If I only update the title (without changing the enum attribute), the entity gets updated as expected:

book.setTitle("Book1");
bookDao.save(book);

I'm puzzled as to why updating the enum attribute results in an insertion rather than an update. Has anyone encountered this issue or can provide insights on what might be causing this?

I attempted to update an existing Book entity's attributes, including an enum attribute, using JPARepository in Spring Boot 3. Specifically, after fetching the Book object, I modified its title and its Type (an enum attribute), and then invoked the .save() method to persist the changes.


Solution

  • The correct behavior is indeed to update the entity. It seems that after saving the entity, another function I have is executing a findByType. However, because the Type is changed, it doesn't recognize the updated entity and ends up saving a new one instead. Ensure that any subsequent functions after the save operation are correctly handling the updated attributes.