title: Spring Boot JPA@CreatedDate @LastModifiedDate not being populated when saving the object
body: <p>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. This is not working. The record that is being saved has "null" for both createdDate and lastModifiedDate.</p>
  
  <p>Here is all the relevant code in Kotlin:</p>
  
  <pre><code>@Entity
  @Table(name = "app_user")
  @EntityListeners(AuditingEntityListener::class)
  data class User(
          @Id
          @GeneratedValue(strategy = GenerationType.AUTO)
          @Column(name = "id")
          val id: UUID? = null,
  
          @NotNull
          @Column(unique = true)
          val email: String,
          val name: String,
          private val password: String,
  
          @CreatedDate
          @Column(name = "created_date", nullable = false, updatable = false)
          var createdDate: LocalDateTime? = null,
  
          @LastModifiedDate
          @Column(name = "last_modified_date", nullable = false)
          var lastModifiedDate: LocalDateTime? = null
  )
  </code></pre>
  
  <p>My SQL queries to add the date fields look like this:</p>
  
  <pre><code>ALTER TABLE app_user
  ADD COLUMN last_modified_date TIMESTAMP,
  ADD COLUMN created_date TIMESTAMP;
  </code></pre>
  
  <p>I also have a configuration class</p>
  
  <pre><code>@Configuration
  @EnableJpaAuditing(auditorAwareRef = "auditorProvider")
  class JpaAuditingConfiguration {
  
      @Bean
      fun auditorProvider(): AuditorAware&lt;String&gt; {
          return AuditorAware { Optional.of(SecurityContextHolder.getContext().authentication.name) }
      }
  
  }
  </code></pre>
  
  <p>And my test class:</p>
  
  <pre><code>  @Autowired
      private lateinit var userRepository: UserRepository
  
      val user = User(
              email = "email",
              name = "name",
              password = "password"
      )
  
      @Test
      fun `it sets the timestamps when a user is created`() {
          userRepository.save(user)
          user.let {
              assertThat(it.createdDate).isNotNull()
              assertThat(it.lastModifiedDate).isNotNull()
          }
      }
  </code></pre>
  
  <p><strong>UPDATE:</strong> </p>
  
  <p>It seems the problem only happens in tests. It seems to be fine when i execute the same code to create a user in the development environment and not in tests.</p>
  
  <p>Do i need some additional config in the tests?</p>
  
  <p><strong>UPDATE 2</strong></p>
  
  <p>I also tried to use the entity manager like this:</p>
  
  <pre><code>@Autowired
  lateinit var entityManager: TestEntityManager
  </code></pre>
  
  <p>Then in the test do:</p>
  
  <pre><code>entityManager.persist(user)
  entityManager.flush()
  </code></pre>
  
  <p>And also </p>
  
  <pre><code>entityManager.persistAndFlush(user)
  </code></pre>
  
  <p>Still is not populating the timestamps.</p>