EJB3Unit保存功能并不能真正保存我的实体

问题描述:

我正在使用ejb3unit session bean test在ejb3项目上进行测试。以下测试将在最后的assertNotSame()检查中失败。EJB3Unit保存功能并不能真正保存我的实体

public void testSave() { 
    Entity myEntity = new Entity(); 
    myEntity.setName("name1"); 
    myEntity = getBeanToTest().save(myEntity); 
    assertNotSame("id should be set", 0l, myEntity.getId()); 
    // now the problem itself ... 
    int count = getBeanToTest().findAll().size(); 
    assertNotSame("should find at least 1 entity", 0, count); 
} 

那么,发生了什么事情。 save(实体)方法为我的“持久化”对象提供了一个id集。但是,当我尝试使用findAll()来查找对象时,它不会提供单个结果。我怎样才能让我的ServiceBean.save方法工作,所以可以找到持久的实体?

编辑

我ServiceBean看起来像这样

@Stateless 
@Local(IMyServiceBean.class) 
public class MyServiceBean implements IMyServiceBean { 

    @PersistenceContext(unitName = "appDataBase") 
    private EntityManager em; 

    public Entity save(Entity entity) { 
    em.merge(entity); 
    } 
    public List<Entity> findAll() { 
    ... uses Query to find all Entities .. 
    } 
} 

和ejb3unit的ejb3unit.properties:

ejb3unit_jndi.1.isSessionBean=false 
ejb3unit_jndi.1.jndiName=project/MyServiceBean/local 
ejb3unit_jndi.1.className=de.prj.MyServiceBean 

也许你没有运行的事务,因此您的实体不保存。

一种方法是通过在测试中注入@PersistenceContext来手动启动事务,但更好地查找ejb3unit中的自动事务管理。

+0

可能会有使用问题:@PersistenceContext(unitName =“appDataBase”)? – justastefan 2010-02-11 17:36:58

+0

而不是。你是否检查你是否有正在运行的交易? – Bozho 2010-02-11 17:51:11

在这里,我们去..

public void testSave() { 
    Entity myEntity = .. // create some valid Instance 
    // ... 
    EntityTransaction tx = this.getEntityManager().getTransaction(); 
    try { 
    tx.begin(); 
    myEntity = getBeanToTest().save(myEntity); 
    tx.commit(); 
    } catch (Exception e) { 
    tx.rollback(); 
    fail("saving failed"); 
    } 
    // ... 
} 

也许这会帮助你们中的一些。