Spring Boot JPA@CreatedDate @LastModifiedDate not being populated when saving the object

后端 未结 4 1174
南笙
南笙 2021-01-17 23:21

I am writing an app with Spring Boot + JPA, using a Postgres database. I have a User Entity and I am trying to get a timestamp when the user record is saved and/or modified.

4条回答
  •  清酒与你
    2021-01-18 00:04

    My prefered solution is a set of multiple annotations to ensure test of @CreatedBy or @CreatedDate:

    @RunWith(SpringRunner.class)
    @DataJpaTest
    @Import(JPAConfig.class)
    @WithMockUser(username = "testuser")
    public class MYRepositoryTest {
    ...
    }
    

    My Entities looks like:

    @MappedSuperclass
    @EntityListeners(AuditingEntityListener.class)
    public class AbstractEntity {
    
        @CreatedBy
        private String createdBy;
    
        @CreatedDate
        private Date createdOn;
    
        @LastModifiedDate
        private Date updatedOn;
    
        @LastModifiedBy
        private String updatedBy;
    }
    

    My JPA configuration is:

    @Configuration
    @EnableJpaAuditing(auditorAwareRef = "auditorAware")
    public class JPAConfig {
    
        @Bean
        public AuditorAware auditorAware() {
            return () -> Optional.of(((User)     SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
        }
    }
    

    Now your audit fields also created during JPA test:

    assertThat(result.getCreatedBy()).isNotNull().isEqualTo("testuser");
    assertThat(result.getCreatedOn()).isNotNull();
    assertThat(result.getUpdatedBy()).isNotNull().isEqualTo("testuser");
    assertThat(result.getUpdatedOn()).isNotNull();
    

提交回复
热议问题