在 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<Instant, Integer> { @Override public Integer convertToDatabaseColumn(Instant attribute) { return (int) attribute.getEpochSecond(); } @Override public Instant convertToEntityAttribute(Integer dbData) { return Instant.ofEpochSecond(dbData); } }
无论选择哪种方法,都能确保在使用 jpa 保存数据时自动将当前秒级时间戳存储在 int(10) 类型的字段中。
以上就是JPA中如何存储秒级时间戳到int(10)类型的字段?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号