Reputation: 647
Here is a quick scenario.
Environment
My Entity
@Entity
@Getter
@Setter
@Table(name = "test_entity")
public class TestEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(insertable = false, updatable = false)
private UUID id;
@CreationTimestamp
@Column(name = "created_at", insertable = false, updatable = false, nullable = false)
private LocalDateTime createdAt;
}
My Repository
public interface TestEntityRepository extends JpaRepository<TestEntity, UUID> {
}
My Test
@DataJpaTest
@EnableAutoConfiguration
@AutoConfigureTestDatabase(replace = Replace.NONE)
@ContextConfiguration(classes = {TestEntityRepository.class})
@EnableJpaRepositories(basePackages = "...")
@EntityScan(basePackages = "...")
public class TestEntityRepositoryTest {
@Autowired
private TestEntityRepository repository;
@Test
public void primaryChangeApplied() {
//given
TestEntity entity = new TestEntity();
TestEntity savedEntity = repository.save(entity);
//when
Optional<TestEntity> entityOptional = repository.findById(savedEntity.getId());
//repository.findAll(); -> The trick is here if I uncomment this test is green
//then
assertTrue(entityOptional.isPresent());
TestEntity result = entityOptional.get();
assertNotNull(result);
assertNotNull(result.getId());
assertNotNull(result.getCreatedAt());
}
}
The problem is that if I uncomment the repository.findAll()
test starts to fail with created_at being null.
Interestingly if I write any custom method in Repository like TestEntity findByCreatedAt(LocalDateTime createdAt);
it mapping createdAt and the test passes.
So its has something to do with finding by id.
UPDATE:
I changed save()
to saveFlush()
, and the test started to pass. Still not clear why.
Upvotes: 1
Views: 355