java TIMESTAMP 列的 H2 数据库默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15166629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:41:53  来源:igfitidea点击:

H2 database default value of TIMESTAMP column

javajpah2

提问by DominikM

I am writing integration tests with H2 database. My database (generated) initialization include this script (because generated join table does not have this column):

我正在使用 H2 数据库编写集成测试。我的数据库(生成)初始化包括这个脚本(因为生成的连接表没有这个列):

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. Even when I inserted a breakpoint on line marked //1 and waited a while - so the time gap between inserts would be significant. (Thread.sleep - same result)

当我在 resultList 中调试此测试时,有两条记录(正确)但它们具有相同的时间戳。即使我在标记为 //1 的行上插入了一个断点并等待了一段时间 - 所以插入之间的时间间隔会很明显。(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?

但结果相同。为什么两个结果都有相同的时间戳?

回答by Thomas Mueller

As documented, the function CURRENT_TIMESTAMPalways returns the same value within a transaction. This behavior matches other databases, for example PostgreSQL.

如文档所述,函数 CURRENT_TIMESTAMP始终在事务中返回相同的值。此行为与其他数据库匹配,例如 PostgreSQL。

回答by Jeremy D

You may add the following annotation to your test to disable transactions.

您可以在测试中添加以下注释以禁用事务。

@Transaction(propagation = Propagation.NEVER)

@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,并且您在其中运行的环境可能还有其他内容。