Search code examples
springjpatestingspring-data-jpa

How to set @CreatedDate in the past (for testing)


My spring-data-jpa backend has a class that populates the (test) database with a lot of test data. The class usese the spring data repositories to create entities. All my entities have a field annotated with @CreatedData and the corresponding @EntityListeners(AuditingEntityListener.class) annotation on the model class. This works fine so far. dateCreated is automatically set correctly.

But when running Junit test I sometimes need to create a (test) object with a dateCreated in the past. How can I archive this? Only via plain JDBC?


Solution

  • I found a way that works for me (using plain JDBC):

    First I create my domain objects for testing with spring-data-jpa:

    MyModel savedModel = myRepo.save(myModel);
    

    That automatically fills the "dateCreated" with timestamp of "now". Since I need creation dates in the past for testing I manually tweak them with plain JDBC:

    @Autowired
    JdbcTemplate jdbcTemplate;
    
    [...]
    
    // This syntax is for H2 DB.  For MySQL you need to use DATE_ADD
    String sql = "UPDATE myTable SET created_at = DATEADD('DAY', -"+ageInDays+", NOW()) WHERE id='"+savedLaw.getId()+"'";
    jdbcTemplate.execute(sql);
    savedModel.setCreatedAt(new Date(System.currentTimeMillis() - ageInDays* 3600*24*1000);
    

    Do not forget to also setCreatedAt inside the returned model class.