gpt4 book ai didi

java - 为什么我的代码没有抛出 EntityExistsException

转载 作者:行者123 更新时间:2023-11-29 00:10:03 25 4
gpt4 key购买 nike

我目前正在研究 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();
}
}

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

最佳答案

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

在 shouldFail2 规范的情况下:

If X is a preexisting managed entity, it is ignored by the persist operation.

并且由于您的 msg 是在该测试中管理的,因此 persist 将被忽略。

您最好切换到提供的 Id 而不是生成以测试 EntityExistsException 案例。

关于java - 为什么我的代码没有抛出 EntityExistsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25612096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com