Jessie
Jessie

Reputation: 67

@CreationTimestamp column sets to null when I update it from POST method

I'm trying to set a field in my database to write the date when a row is modified. To do that, I'm using the anotations provided by Hibernate.

When I create the row via POST method it works fine. It fills both columns (creations and modified) with the same value (obviously).

The problem appears when I update the entity (POST). As a result, the "modified_date" column updates the date but the "created_date" sets to null.

This is my EntityBase that's extended by User entity

@MappedSuperclass
public class EntityBase {

@JsonProperty("_version")
@Column(name="_version")
@Version
private Integer version = 0;

@Column(name= "CREATION_DATE", nullable = false)
@CreationTimestamp
private LocalDateTime createDateTime;

@Column(name= "UPDATED_TIME")
@UpdateTimestamp
private LocalDateTime updateDateTime;

~~ getters & setters ~~

Whenever I do a post, it seems that Hibernate is entering a null value in the generated query, that's the reason of the nullable property in @Column

Here is my User entity

@Entity
@Table(name="user")
public class User extends EntityBase {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@JsonProperty("id")
private String id;

@Column(name="NAME")
@JsonProperty("name")
private String name;

@Column(name="SURNAME")
@JsonProperty("surname")
private String surname;

@Column(name="EMAIL")
@JsonProperty("email")
private String email;

@Column(name="PASSWORD")
@JsonProperty("password")
private String password;

//bi-directional many-to-one association to Client
@ManyToOne
@JoinColumn(name="CURRENT_CLIENT_ID")
@JsonProperty("current_client_id")
private Client currentClientId;

@Column(name="INCORPORATION_DATE")
@JsonProperty("incorporation_date")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone="Europe/Madrid")
private LocalDate incorporationDate;

@Column(name="WORKING_TIME_START")
@JsonProperty("working_time_start")
private LocalTime workingTimeStart;

@Column(name="WORKING_TIME_FINISH")
@JsonProperty("working_time_finish")
private LocalTime workingTimeFinish;

@Column(name="MEAL_TIME")
@JsonProperty("meal_time")
private LocalTime mealTime;

What am I doing wrong? Thanks in advance!

Upvotes: 4

Views: 7859

Answers (1)

Syed Mehtab Hassan
Syed Mehtab Hassan

Reputation: 1337

You can use the following definition to avoid that the field is updated:

@Column(name= "CREATION_DATE", nullable = false, updatable = false)

Upvotes: 18

Related Questions