Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@CreateTimestamp, @UpdateTimestamp. Why is the field "create" null for the returned object?

I have 2 fields: create and update.

@CreateTimestamp
@Column(nullable = false, updatable = false)
private Timestamp create;

@UpdateTimestamp
@Column(nullable = false)
private Timestamp update;

After create object: everything is OK. But during doing update object, I get for the returned object the field "create" is null. In DB an object is saving correct with filled fields. How can it fix?

Full code of class:

@Entity
@Table(name = "user")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserEntity {

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

    @Column(nullable = false, unique = true)
    private String name;

    @Column(nullable = false)
    private String password;

    @CreateTimestamp
    @Column(nullable = false, updatable = false)
    private Timestamp create;

    @UpdateTimestamp
    @Column(nullable = false)
    private Timestamp update;
}

Method update:

public UserEntity update(UserEntity user, String id) {
     UserEntity userFromDB = userDao.findById(id);
     UserEntity updatedUser = userDao.save(userFromDB);
     return updatedUser;
}

When return updatedUser, field create is null.

like image 401
Darkin Rall Avatar asked Nov 25 '25 06:11

Darkin Rall


1 Answers

It's unclear where you have imported @CreateTimestamp and @UpdateTimestamp from.

However, as you seem to be using Spring, you could use @CreatedDate and @LastModifiedDate from Spring Data. And ensure your entity is annotated with @EntityListeners(AuditingEntityListener.class).

Apart from it, since Java 8, with the introduction of the new Date and Time API, you should avoid using Date and related classes such as Timestamp. A suitable replacement for Timestamp, in your situation, would be Instant or OffsetDateTime.

like image 140
cassiomolin Avatar answered Nov 27 '25 18:11

cassiomolin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!