【问题标题】:Why is my code not throwing the EntityExistsException为什么我的代码没有抛出 EntityExistsException
【发布时间】:2014-10-26 01:14:57
【问题描述】:

我目前正在学习 Java EE 7,并试图弄清楚何时会抛出 EntityExistsException。我目前有一个非常简单的带有基本属性的 Message 类。据我了解,当数据库中已经存在具有相同主键的实体时,应该抛出EntityExistsException。我不太确定上述实体是否分离是否重要,因此快速测试了它何时会发生。然而,两个测试用例都通过了某种原因,没有向我显示错误。

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.iys.jpa.mysql.example.Message;
import org.junit.After;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;

public class MessageIT {

    private static EntityManagerFactory emf ; 
    private EntityManager em;
    private EntityTransaction tx;

    public MessageIT() {
    }

    @Before
    public void setUp() {
       emf= Persistence.createEntityManagerFactory("JPAMYSQLExampleU");
        em = emf.createEntityManager();
        tx = em.getTransaction();
        Message m1= new Message("Hello");       
        tx.begin();
        em.persist(m1);        
        tx.commit();
        System.out.println("Setting up the test");
    }

    @After
    public void tearDown() {
        if (em != null) {
            em.close();
        }
    }

    //either one of the test should fail

    @Test
    public void shouldFail1(){
        Message msg = em.find(Message.class, 1L);
        Message copied= msg;    
        copied.setMessage("changed");
        assertTrue(em.contains(msg));
        em.clear();
        assertFalse(em.contains(msg));
        assertFalse(em.contains(copied));  //both entities are currently detached
        tx.begin();
       em.persist(copied);

        tx.commit();

    }
    @Test
    public void shouldFail2(){
        Message msg = em.find(Message.class, 1L);
        assertTrue(em.contains(msg));
        tx.begin();
        em.persist(msg);
        tx.commit();
    }
}

如果我误解了错误发生的条件,您将如何更改代码以引发上述错误。

【问题讨论】:

  • 附注db中的测试结果有3个不同的行(1, Hello), (2, changed), (3, Hello)
  • 现在是凌晨 4 点 50 分,过去 5 个小时里,我一直在为此苦苦挣扎,翻阅有关 stackoverflow 的书籍和类似问题。我现在要睡觉了。我将不胜感激有关此事的任何意见。谢谢

标签: java mysql jakarta-ee exception jpa


【解决方案1】:

您可能正在使用 @GeneratedValue 作为您的 ID(如果您可以在问题中提供您的实体实现会很好)。在这种情况下,具有持久性的提供者可能只是在持久化实体之前生成新的 id。 (这就是为什么 shouldFail1 不会失败)。

如果是 shouldFail2 规范状态:

如果 X 是一个预先存在的托管实体,它会被持久化忽略 操作。

并且由于您的 msg 在该测试中被管理,persist 被简单地忽略。

您最好切换到提供的 Id 而不是生成来测试 EntityExistsException 的情况。

【讨论】:

  • 非常感谢。正如你所建议的,Id 确实是 GeneratedValue。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多