我的文件有字段-
<property name="createdTs" type="timestamp">
<column name="created_ts" length="29" />
</property>
当我用 - 保存表格时
public void persist(DrRequest transientInstance) {
log.debug("persisting DrRequest instance");
try {
Transaction trans=sessionFactory.getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession().persist(transientInstance);
trans.commit();
log.debug("persist successful");
} catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
它不会在 postgresql 数据库表中保存包含当前时间的 created_ts
字段。
created_ts
的类型是timestamp without time zone
。
最佳答案
如果您使用 hibernate.hbm2ddl.auto 生成数据库架构,您需要指示 Hibernate 包含默认的“CURRENT_TIMESTAMP”指令:
<column name="created_ts" length="29" sql-type="timestamp without time zone" default="CURRENT_TIMESTAMP"/>
如果您有一个现有架构,则需要更改它以为此时间戳列添加默认值。
Hibernate 不会知道数据库生成的值,因此您需要在持久化实体并刷新 Hibernate session 后刷新实体:
session.flush();
session.refresh(transientInstance);
这样您就可以重新加载实体并获取数据库生成的值。
关于java - 如何使用 hibernate 映射插入当前时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28083833/