[英]H2 database default value of TIMESTAMP column
I am writing integration tests with H2 database.我正在使用 H2 数据库编写集成测试。 My database (generated) initialization include this script (because generated join table does not have this column):
我的数据库(生成)初始化包括这个脚本(因为生成的连接表没有这个列):
ALTER TABLE INT_USR ADD IU_INSDTTM TIMESTAMP DEFAULT NOW();
This is how I create records:这就是我创建记录的方式:
Integration integrationOne = createIntegration(firstId, "FIRST");
Integration integrationTwo = createIntegration(secondId, "SECOND");
flushAndClear();
userService.logRecentIntegration(integrationOne.getId(), user.getId());
flushAndClear();
userService.logRecentIntegration(integrationTwo.getId(), user.getId()); //1
The method logRecentIntegrations(.., ..) just calls the DAO and the dao does this:方法 logRecentIntegrations(.., ..) 只是调用 DAO 并且 dao 这样做:
Query query = entityManager.createNativeQuery(
"INSERT INTO INT_USR (USR_ID, INT_ID) VALUES (?, ?)");
query.setParameter(1, userId)
.setParameter(2, integrationId);
query.executeUpdate();
Later in my test:后来在我的测试中:
Query query = entityManager.createNativeQuery(
"SELECT * FROM INT_USR ORDER BY IU_INSDTTM");
List resultList = query.getResultList();
When I debug this test in resultList there are two records (correct) but they have same timestamp.当我在 resultList 中调试此测试时,有两条记录(正确)但它们具有相同的时间戳。 Even when I inserted a breakpoint on line marked //1 and waited a while - so the time gap between inserts would be significant.
即使我在标记为 //1 的行上插入了一个断点并等待了一段时间 - 所以插入之间的时间间隔会很明显。 (Thread.sleep - same result)
(Thread.sleep - 结果相同)
I tried to modify the SQL script to我试图将 SQL 脚本修改为
ALTER TABLE INT_USR ADD IU_INSDTTM TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
But with same result.但结果相同。 Why both results have same timestamp?
为什么两个结果都有相同的时间戳?
As documented, the function CURRENT_TIMESTAMP always returns the same value within a transaction.如文档所述,函数 CURRENT_TIMESTAMP始终在事务中返回相同的值。 This behavior matches other databases, for example PostgreSQL.
此行为与其他数据库匹配,例如 PostgreSQL。
You may add the following annotation to your test to disable transactions.您可以在测试中添加以下注释以禁用事务。
@Transaction(propagation = Propagation.NEVER)
Note: That annotation comes from Spring and there may be something else for the environment that you are running within.注意:该注解来自 Spring,并且您在其中运行的环境可能还有其他内容。
Note that if you're generating hibernate pojo's you can also use CreationTimestamp
.请注意,如果您要生成休眠 pojo,您还可以使用
CreationTimestamp
。 I just tried it and it seemed to work!我刚试过,它似乎奏效了!
@CreationTimestamp
protected LocalDateTime createdDate;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.