【发布时间】: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=h2spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialectspring.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