iftekhar iftekhar
iftekhar iftekhar

Reputation: 103

Current timeStamp is not getting automatically saved into the table with jpa

I am using the below sql query to create a table in postgres DB.

CREATE TABLE IF NOT EXISTS data
(
    id serial, 
    created_at timestamp(0) without time zone DEFAULT (now())::timestamp(0) without time zone,
    created_by integer NOT NULL
);

Entity Class:-

@Entity
@Table(name = "data")
@Getter
@Setter
public class Data implements Serializable {
    private static final long serialVersionUID = 7462797749946000617L;

    public Data() {
    }

    public Data(Integer createdBy) {
        super();
        this.setCreatedBy(createdBy);
    }

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "created_at")
    private Timestamp createdAt;

    @Column(name = "created_by")
    private Integer createdBy;
}

When i am inserting the data like Date data=new Data("12312442");

LogsRepository.save(data);

The 'created_at' value is getting saved as null value in DB. Can anyone tell me what wrong am i doing?

Upvotes: 1

Views: 4249

Answers (2)

Cepr0
Cepr0

Reputation: 30474

For fields which values are populated on DB layer you can use Hibernate annotation @Generated that tells the Hibernate to read such values after persisting the entity. In your case:

@Column(name = "created_at")
@Generated(GenerationTime.INSERT)
private Timestamp createdAt;

Note then you invoke logsRepository.save(data) the Hibernate creates two query to DB: first - insert new data:

insert into data values(...)

second - read the generated value:

select created_at from data where id = ...

Upvotes: 2

crizzis
crizzis

Reputation: 10726

You could try using @Column(insertable = false), to force JPA to ignore the column when generating INSERT statements, so that the default db value would apply.

However, assuming you are using spring data, why not simply @EnableJpaAuditing and then annotate the property with @CreatedDate?

Note that you could then handle createdBy in a similar way, by annotating it with @CreatedBy and providing an AuditorAware.

AuditorAware integrates nicely with Spring Security. Here's an example implementation:

@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {
        return Optional
                    .ofNullable(SecurityContextHolder.getContext().getAuthentication())
                .filter(auth -> !(auth instanceof AnonymousAuthenticationToken))
                .map(Authentication::getPrincipal)
                .map(UserDetails.class::cast)
                .map(UserDetails::getUsername);
    }

}

Upvotes: 1

Related Questions