Updated update Hibernate updatable = false UUID

I am using Spring Data JPA with Hibernate, and I am having problems with the updated = false property in the @Column annotation.

I have a base class for all my @Entity objects with a UUID defined as follows:

 @MappedSuperclass @Getter @Setter @EqualsAndHashCode(of= {"uuid"}) public abstract class AbstractEntity implements Persistable<Long> { @Id @GeneratedValue(strategy = AUTO) @Column(unique = true, updatable = false) private Long id; @Column(unique = true, updatable = false) private UUID uuid = UUID.randomUUID(); } 

Note the annotation updatable = false .

To verify that the UUID field is NOT actually updated, I wrote this test:

 @Test public void testChangeUUID() { User user = userRepo.findOne(1L); assertNotNull(user); assertEquals(USER_UUID, user.getUuid().toString()); final UUID newUuid = UUID.randomUUID(); user.setUuid(newUuid); user = userRepo.save(user); assertEquals(newUuid, user.getUuid()); User user2 = userRepo.findOne(1L); assertNotNull(user2); assertEquals("UUID should not have changed", USER_UUID, user2.getUuid().toString()); } 

I really expected the exception to be thrown by calling userRepo.save(user) , but that won't happen. Instead, the final assertEquals() , which means the UUID has actually been updated.

Is this the expected behavior? Is there a way to prevent a change in UUID?

+6
source share
1 answer

According to the documentation, the updatable property decided whether this column would be part of the update statement. This means that Hibernate ignores it when sending updates to the database. Thus, the state in memory and the state of the database will be different.

To verify this, try to clear the session (expulsion) before calling User user2 = userRepo.findOne(1L)

+5
source

Source: https://habr.com/ru/post/979642/


All Articles