H2 database default value of TIMESTAMP column

我们两清 提交于 2019-12-23 09:00:19

问题


I am writing integration tests with H2 database. 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:

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)

I tried to modify the SQL script to

ALTER TABLE INT_USR ADD IU_INSDTTM TIMESTAMP DEFAULT CURRENT_TIMESTAMP;

But with same result. Why both results have same timestamp?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/15166629/h2-database-default-value-of-timestamp-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!