I have the following JPA entity and test:
@Entity
@Table(name = "T_USER")
@Getter
@NoArgsConstructor
@AllArgsConstructor
public final class User
{
@Id
@Column(updatable = false)
private long id;
@Setter
@Column(updatable = false, insertable = false)
private String name;
}
@DataJpaTest(showSql = true)
class TestUserRepository
{
@Autowired
private UserRepository repository;
@Test
public void testCreateUser()
{
repository.saveAndFlush(new User(101, "John Doe"));
final var optional = repository.findById(101L);
assertTrue(optional.isPresent());
var user = optional.get();
assertNull(user.getName());
}
}
Since I annotate name with @Column(updatable = false, insertable = false), I expect it to be null after queried, which is not, although the data in table is actually null.
My understanding is that the repository actually load entity from 1st level cache instead of actually hitting the DB hence the behavior.
My question is how to properly write test for this case?
Any help would be greatly appreciated.
Best Regards,
Mike
The goal of using
insertable=false or/and updatableis not to prevent the updating of an attribute in a table (it already doesn't work) but to indicate to jpa to ignore this field by displaying associated request for insert or/and update query. To see that, add these properties to show executed requests for your test.In certain cases, this can allow you to leave another entity, database or another program handle concened field. you can check this post for more information about that. Additionally more information about Column annotation.
If the purpose of your code is to realy prevent update or insertable for an entity field you can do it by coding some kind of exlplicit validator for
name fieldbefore save or/and update onUser entity.Hope this could be helpful.