【发布时间】:2019-04-13 17:14:54
【问题描述】:
我正在使用 Hibernate @Check 注释,但在不满足约束时不能让我的测试失败。目前只是使用带有 H2 数据库的默认 Spring boot 配置。
我错过了什么? save(..) 之后应该有某种 flush 吗?
运行测试时,我看到表创建正确。如果我从日志中复制创建行并使用它为我的“真实”Postgres 数据库创建一个表,我可以测试不同的插入,并看到该行在约束条件下一切正常。
实体
@Getter @Setter
@Entity @Check(constraints = "a IS NOT NULL OR b IS NOT NULL")
public class Constrained {
@Id @GeneratedValue
private Long id;
private String a, b;
}
测试
@DataJpaTest
@RunWith(SpringRunner.class)
public class HibernateCheckTest {
@Resource // this repo is just some boiler plate code but attached at
// the bottom of question
private ConstrainedRepository repo;
@Test @Transactional // also tried without @Transactional
public void test() {
Constrained c = new Constrained();
repo.save(c); // Am I wrong to expect some constraint exception here?
}
}
运行测试时的表格生成脚本
创建表受限(id bigint 不为空,a varchar(255),b varchar(255), 主键 (id), 检查 (a IS NOT NULL OR b IS NOT 空))
Repository(在 repo 中没什么可看的,只是为了展示它):
public interface ConstrainedRepository
extends CrudRepository<Constrained, Long> {
}
但是
如果我使用EntityManager,那么添加到我的测试类中:
@PersistenceContext
private EntityManager em;
并像这样坚持:
em.persist(c);
em.flush();
而不是repo.save(c) 我会得到异常。
与
使用repo.save(c) 更仔细地研究原始测试的日志:
org.springframework.test.context.transaction.TransactionContext:139 - 为测试回滚事务:
...
testException = [null],
所以由于某种原因,这个错误只是被包装和记录了。使用存储库进行持久化时如何将其“解包”并抛出?
【问题讨论】:
标签: java hibernate spring-boot jpa h2