【问题标题】:How to use MySQL-specific functions in H2 database?如何在 H2 数据库中使用 MySQL 特有的函数?
【发布时间】:2019-02-12 12:19:39
【问题描述】:

如何将包含 @Formula 字段的实体持久保存到 H2 数据库?

我遇到以下异常:

...
Caused by: org.h2.jdbc.JdbcSQLException: Function "UNIX_TIMESTAMP" not found;
...

岗位类:

@Entity
public class Post {
    // ...

    @Formula("UNIX_TIMESTAMP(creation_date_time) / 24 * 60 * 60 * 1000 + likes_count")
    private long score;

    // ...
}

PostRepositoryTest 类:

@ExtendWith(SpringExtension.class)
@DataJpaTest
class PostRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private PostRepository postRepository;

    @Test
    void savePost() {
        entityManager.persist(new Post());

        List<Post> posts = postRepository.findAll();

        assertEquals(1, posts.size());
    }
}

【问题讨论】:

  • UNIX_TIMESTAMP 特定于 MySQL,H2 不自动支持。
  • 如果用MODE=MYSQL启动H2嵌入式数据库会怎样?
  • 我在 application-test.properties 中添加了这些:spring.jpa.database=h2 spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect spring.datasource.url=jdbc:h2:mem:testDB;MODE=MYSQL 并在测试类中添加了@ActiveProfiles("test")。现在我得到以下异常:org.h2.jdbc.JdbcSQLException: Table "POST" not found; SQL statement

标签: spring unit-testing spring-boot h2 spring-test


【解决方案1】:

根据https://h2database.com/html/features.html#user_defined_functions,你可以在src/test/resources/import.sql中定义这样一个函数:

CREATE ALIAS IF NOT EXISTS UNIX_TIMESTAMP FOR "acme.H2Function.unixTimestamp";

并定义这个类:

package acme;

public class H2Function {

  public static long unixTimestamp(java.sql.Timestamp timestamp) {
    return timestamp.getTime() / 1000L;
  }
}

Spring JPA 将在您开始单元测试时自动调用 import.sql。

注意:必须命名 import.sql,而不是 schema.sql,而不是 data.sql

【讨论】:

    猜你喜欢
    • 2016-02-27
    • 2016-12-03
    • 2020-07-02
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多