将 LocalDateTime 设置为使用 hibernate 4.3.10 自动生成

Set LocalDateTime to autogenerate with hibernate 4.3.10

目前我有一个基本实体如下:

@MappedSuperclass
public abstract class BaseEntity {
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    private Long id;
    private boolean deleted;

    @Convert(converter = LocalDateTimePersistenceConverter.class)
    private LocalDateTime createdAt;
    @Convert(converter = LocalDateTimePersistenceConverter.class)
    private LocalDateTime updatedAt;
}

是否可以用某些东西注释 LocalDateTime 以使数据库默认为当前日期和时间?

p.s。我不允许使用 hibernate 5.

您可以使用@PrePersist 注释。

Executed before the entity manager persist operation is actually executed or cascaded. This call is synchronous with the persist operation.

示例:

  @PrePersist
  protected void onCreate() {
    createdAt = new LocalDateTime();
    updatedAt = new LocalDateTime();
  }

如果您认为合适,您还可以使用 @PreUpdate 注释。

阅读更多关于events that occur inside hibernate's persistence mechanism

@LaurentiuL 是正确的。
但我认为下面应该也有效

@Convert(converter = LocalDateTimePersistenceConverter.class)
private LocalDateTime createdAt = new LocalDateTime ();
@Convert(converter = LocalDateTimePersistenceConverter.class)
private LocalDateTime updatedAt= new LocalDateTime ();

这个问题的答案也应该对你有帮助:Creation timestamp and last update timestamp with Hibernate and MySQL