Spring Data JPA Repository Test Behavior With @DataJpaTest

47 views Asked by At

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

1

There are 1 answers

0
Oscar On

The goal of using insertable=false or/and updatable is 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.

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

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 field before save or/and update on User entity.

Hope this could be helpful.