如何将包含 @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());
}
}
最佳答案
根据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。
NOTE: Must naming import.sql, not schema.sql, not data.sql
关于spring - 如何在H2数据库中使用MySQL特有的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52217563/