Giannis Pappas
Giannis Pappas

Reputation: 137

Hibernate and MySQL: @CreationTimestamp annotated Date property throws ConstraintViolationException when saving new Entity

I'm making a Spring MVC app with Hibernate and MySQL. I have a TIMESTAMP column in one of my MySQL tables defined like this tstamp timestamp default current_timestamp. The entity for this table has a composite primary key which includes the tstamp column.

The Entity class part where I define the EmbeddedId:

@Entity
@Table(name="trustassessments")
public class TrustAssessment {

    @EmbeddedId
    @JsonView(Views.Public.class)
    private TrustAssessmentId id;
    ....

The Embeddable class where I define the timestamp:

@Embeddable
public class TrustAssessmentId implements Serializable {

    @Column(name="deviceId")
    int deviceId;

    @Column(name="tmsId")
    int tmsId;

    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="tstamp")
    private Date tstamp;
    ....

I'm using Jackson, so I POST in json format and I have tried these two:

1.

{
    "id": {
        "deviceId": 21,
        "tmsId": "20"
    },
    "trustLevel": 0.4,
    "honesty": 0.6,
    "cooperativeness": 0.4,
    "communityInterest": 0.2
}

2.

{
    "id": {
        "deviceId": 21,
        "tmsId": "20",
        "tstamp": ""
    },
    "trustLevel": 0.4,
    "honesty": 0.6,
    "cooperativeness": 0.4,
    "communityInterest": 0.2
}

The stack trace:

Nov 28, 2019 9:07:28 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN: SQL Error: 1048, SQLState: 23000 Nov 28, 2019 9:07:28 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR: Column 'tstamp' cannot be null Nov 28, 2019 9:07:28 PM org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure ERROR: HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement] Nov 28, 2019 9:07:28 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/tms-rest-again] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause java.sql.SQLIntegrityConstraintViolationException: Column 'tstamp' cannot be null at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)

Upvotes: 0

Views: 1085

Answers (1)

Giannis Pappas
Giannis Pappas

Reputation: 137

I removed the @CreationTimestamp and wrote it like this:

@Column(name="tstamp", updatable=false)
@Temporal(TemporalType.TIMESTAMP)
private Date tstamp = new Date();

Props to this answer.

However, it would be nice if someone could explain how this works and why it didn't work with @CreationTimestamp.

Upvotes: 1

Related Questions