@Data
@Buider
@NoArgsConstructor
@AllArgsConstructor
@Embeddable
public class ComplexPkey {
@Column(name = "pkey", nullable = false)
public Long pkey;
@CreationTimestamp(source = SourceType.DB)
@Column(name = "create_timestamp", nullable = false)
public Date createTimestamp;
@UpdateTimestamp(source = SourceType.DB)
@Column(name = "update_timestamp", nullable = false)
public Date updateTimestamp;
}
@Getter
@Setter
@Entity
@Builder
@NoArgsConstuctor
@AllArgsConstructor
public class ComplexEntity {
@EmbeddedId
private ComplexPkey pkey;
private String fieldExample;
}
When using Spring JPA's save()
method, I encountered a constraint error related to the timestamp fields in the embedded ID. However, when the timestamps are placed directly in the ComplexEntity
, the save()
operation is successful.
Is it possible to use annotations like @CreationTimestamp
and @UpdateTimestamp
in an @EmbeddedId
, or is there another way to retrieve the timestamp data from the database for a saved entity? (database is PostgreSQL)
I tried relocating the fields to the main class, and it helped, but the main point is that I need these fields specifically in the @EmbeddedId
It seems like Hibernate doesn't support @CreationTimestampt
and @UpdateTimestamp
in Embeddables. You can take a look here: https://discourse.hibernate.org/t/java-exception-when-using-creationtimestamp-or-updatetimestamp-annotation-in-embeddable/699
Vlad Mihalcea proposes a solution: to try @PrePersist
and @PreUpdate
, like here: https://vladmihalcea.com/prepersist-preupdate-embeddable-jpa-hibernate/