我目前正在學習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();
}
}
如果我誤解錯誤發生的條件,那麼如何更改代碼以便引發上述錯誤。
p.s.測試結果分貝(1,你好),(2,更改),(3,你好)中的3個不同的行 – user3442960 2014-09-01 19:48:13
現在是凌晨4點50分,我在過去的5個小時裏通過書籍和類似的東西摔跤關於計算器的問題。我現在要睡覺了。我將很感激任何關於此事的投入。謝謝 – user3442960 2014-09-01 19:52:33