Portable default to current datetime with JPA

Viewed 318

I wrote for my column

class MyEntity {

    @Column(columnDefinition="DATETIME(6) DEFAULT CURRENT_TIMESTAMP")
    private LocalDateTime createdDate = LocalDateTime.now(ZoneOffset.UTC);

and it works in MySQL but fails in H2 which I use for automated testing.

Is it possible to have default datetime serverside with JPA which is portable?

1 Answers

Avoiding the problem by avoiding the "test database" H2

I would generally recommend to test your code using testcontainers rather than with H2 to avoid any issues purely caused by translation,

Using a proxy to translate your SQL

If for some reason you need multi RDBMS support (possibly not just with H2), you could hook jOOQ's ParsingConnection or DataSource in between when you generate your schema or run your JPA native SQL queries to make sure (most) MySQL specific stuff also works on H2.

I've written a blog post on the jOOQ blog to explain how this could work.

Related