加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Hibernate JPA持久性异常

发布时间:2020-12-15 02:18:51 所属栏目:Java 来源:网络整理
导读:我正在尝试基于一组给定的JUnit测试来测试我的hibernate映射.但是,以下测试失败了. @Testpublic void testEntity3Constraint() { expectedException.expect(PersistenceException.class); expectedException.expectCause(isA(ConstraintViolationException.c
我正在尝试基于一组给定的JUnit测试来测试我的hibernate映射.但是,以下测试失败了.

@Test
public void testEntity3Constraint() {
    expectedException.expect(PersistenceException.class);
    expectedException.expectCause(isA(ConstraintViolationException.class));

    EntityTransaction tx = em.getTransaction();
    tx.begin();
    try {
        // Entity #3
        IUplink ent3_1 = daoFactory.getUplinkDAO().findById(testData.entity3_1Id);
        ent3_1.setName(TestData.N_ENT3_2);
        em.persist(ent3_1);
        em.flush();

    } finally {
        tx.rollback();
    }
}

这是我得到的例外:

Expected: (an instance of javax.persistence.PersistenceException and exception with cause is an 
     instance of org.hibernate.exception.ConstraintViolationException)
but: exception with cause is an instance of org.hibernate.exception.ConstraintViolationException cause 
     <org.hibernate.PersistentObjectException: detached entity passed to persist: dst.ass1.jpa.model.impl.UplinkImpl> 
     is a org.hibernate.PersistentObjectException

正如您所看到的,Constraint Violations和Persistence Exceptions在实例和原因方面进行了交换.当我调用entitymanager.persist时抛出异常.我怎样才能获得预期的例外?

我不能改变预期的异常,也不想改变.我需要找到一种方法来获得测试所期望的异常.

提前致谢!

解决方法

您期待javax.persistence.PersistenceException
但得到一个类似但不同的org.hibernate.PersistentObjectException.

只需更改测试中的预期异常即可.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读