hibernate UPDATE_TIMESTAMP不会在表更新时自动更新

rqcrx0a6  于 2022-11-14  发布在  其他
关注(0)|答案(2)|浏览(116)

我有一张table,看起来像这样:

CREATE TABLE `test_table` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `ref_id` bigint(20) NOT NULL,
  `count` int(11) DEFAULT NULL,
  `status` tinyint(4) NOT NULL,
  `create_timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `update_timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1

POJO:

@Entity
@Data
@Table(name = "test_table")
public class TestTable implements Serializable {
    private static final long serialVersionUID = 4273269337137129245L;

    @Id
    @Column(name = "id")
    @GenericGenerator(name = "assigned-identity", strategy = "com.paytm.pgplus.datasource.custom.AssignedIdentityGenerator")
    @GeneratedValue(generator = "assigned-identity", strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "ref_id")
    private Long refId;

    @Column(name = "count")
    private Integer count;

    @Column(name = "status")
    @Enumerated(EnumType.ORDINAL)
    private Status status;

    @Column(name = "create_timestamp")
    @Temporal(TemporalType.TIMESTAMP)
    private Date createTimeStamp;

    @Column(name = "update_timestamp")
    @Temporal(TemporalType.TIMESTAMP)
    private Date updateTimeStamp;
}

我正在使用Hibernate更新这个表。我正在更新status列,该列已成功更新。但预期的是,每当test_table中的任何列被更新时,update_timestamp列也应该相应地更新,但这并没有发生。
我错过了什么吗?

wgx48brx

wgx48brx1#

尝试将POJO中的updateTimeStamp更新为:

@Generated(GenerationTime.ALWAYS)
@Column(name = "updateTimeStamp")
@Temporal(TemporalType.TIMESTAMP)
private Date updateTimeStampt;
fae0ux8s

fae0ux8s2#

实际上,我们需要告诉Hibernate,我们希望在更新时更新该列。
为此,请使用@CreationTimestamp(将在插入记录时设置)和@UpdateTimestamp(将在更新记录时设置)。

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

@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "update_timestamp")
private Date updateTimestamp;

相关问题