7
votes

I have a very confusing problem stealing a lot of time:

@Column(name = "created", columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP", insertable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date created;

This code the timestamp is set in my Postgres DB but the repository returns a entity with created = null;

I've tried some annotations like:

@Generated

from : Spring Data JPA JpaRepository.save(entity) not returning database default values

But nothing worked for me.

2
Did you try the @GeneratedValue annotation?Kayaman

2 Answers

9
votes

The generated values are only guaranteed to be generated at flush time. Saving an entity only makes it "attached" to the persistence context. So, either you have to flush the entity manager explicitely.

Try to use entity.saveAndFlush() and it should work.

4
votes

Using Spring Data we were facing the same issue with sql server

We solved it using

import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;

@Generated(GenerationTime.INSERT)
@Column(name = "created", insertable = false, updatable = false)
private LocalDateTime created;

You can combine it saveAndFlush (From JpaRepository)

If nothing works you can either implement refresh method by extending SimpleJpaRepository or avoid using the database default and replace it with an EntityListener

@EnableJpaAuditing
public class ConfigClass {...}


@EntityListeners(AuditingEntityListener.class)
public class YourEntity {

    @Column(name = "created", insertable = false, updatable = false)
    @CreatedDate
    private LocalDateTime created;
}

Take in consideration that using EntityListener you have to remove the database default. You could set insertable=true and use ColumnTransformer

    @Column(name = "created", updatable = false)
    @ColumnTransformer(write = "coalesce(sysutcdatetime(), ?)")
    @CreatedDate
    private LocalDateTime created;