2014-09-01 58 views
1

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

如果我误解错误发生的条件,那么如何更改代码以便引发上述错误。

+0

p.s.测试结果分贝(1,你好),(2,更改),(3,你好)中的3个不同的行 – user3442960 2014-09-01 19:48:13

+0

现在是凌晨4点50分,我在过去的5个小时里通过书籍和类似的东西摔跤关于计算器的问题。我现在要睡觉了。我将很感激任何关于此事的投入。谢谢 – user3442960 2014-09-01 19:52:33

回答

1

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

而且在shouldFail2规格的情况下规定:

如果X是一个已经存在的管理实体,它是由持续 操作忽略。

并且由于您的msg在该测试中进行管理,因此坚持将被忽略。

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

+0

非常感谢。如你所说,Id的确是GeneratedValue。 – user3442960 2014-09-02 02:56:04