[英]Why is my code not throwing the EntityExistsException
我目前正在研究Java EE 7,並試圖確定何時拋出EntityExistsException
。 我目前有一個非常簡單的Message類,具有基本屬性。 據我了解,當數據庫中已經存在具有相同主鍵要EntityExistsException
的實體時,應拋出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(如果可以在問題中提供實體實現,那將是很好的選擇)。 在這種情況下,具有persist的提供者可能只是在持久實體之前生成新的id。 (這就是為什么shouldFail1不會失敗)。
並且在shouldFail2規范中指出:
如果X是一個預先存在的管理實體,則persist操作將忽略它。
並且由於在該測試中對您的msg
進行了管理,因此將忽略持久性。
您最好切換到提供的ID而不是生成以測試EntityExistsException
情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.