如何将其中包含@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());
}
}
答案 0 :(得分: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