在 jpa 中存储秒级时间戳
在 jpa 中自动存储数据时通常使用 creationtimestamp 或 createddate 注解,但这些注解只能与 timestamp、date、instant 或 long 类型字段一起使用。
对于 int(10) 类型的秒级时间戳字段,可以采用以下方法:
-
自定义实体监听器
创建一个实体监听器,在 @prepersist 事件中手动将当前时间戳转换为 int(10) 类型。具体实现如下:
@entitylisteners(myentitylistener.class) public class myentity { private int createtime; // ... } public class myentitylistener { @prepersist public void prepersist(myentity entity) { entity.setcreatetime((int) instant.now().getepochsecond()); } } -
使用 @converter 注解
使用 jpa 的 @converter 注解将 instant 类型转换为 int(10) 类型。具体实现如下:
@Entity public class MyEntity { @Converter(converterClass = InstantToIntConverter.class) private int createTime; // ... } @Converter public class InstantToIntConverter implements AttributeConverter{ @Override public Integer convertToDatabaseColumn(Instant attribute) { return (int) attribute.getEpochSecond(); } @Override public Instant convertToEntityAttribute(Integer dbData) { return Instant.ofEpochSecond(dbData); } }
无论选择哪种方法,都能确保在使用 jpa 保存数据时自动将当前秒级时间戳存储在 int(10) 类型的字段中。










