当前位置: 动力学知识库 > 问答 > 编程问答 >

java ee - Can't find entities in PersistenceContext after .persist()

问题描述:

I am writing a JavaEE Project and am trying to get some unit tests on the way. The unit testing framework we use is JUnit, alongside Maven and Hudson for building and CI.

Among other tests, I'd like to test the JPA-2.0 query logic, as this is one of the core functionalities of our project. We implemented quite sophisticate query logic which also allows the user to make mistakes, spell things wrongly etc. so we want to make shure that this works.

The queries themselves are dynamically constructed using the JPA-2.0 Criteria API and Metamodel API.

Now, in my unit test, I set up persistence and created an EntityManager like this:

protected static EntityManagerFactory emf;

protected static EntityManager em;

emf = Persistence.createEntityManagerFactory("persistenceUnitName");

em = emf.createEntityManager();

This works and I can also query the DB - but that's not what I want.

What I'm trying to do:

As we do not want testing-data in the DB, the plan is to first create some entities, then persist them. Then we'd run our queries and make sure we get the right results. Finally, as the unit testing persistence does not run in a transaction the entities are never persisted to DB, and the DB remains unchanged (which is what we want).

Entity entity = new Entity();

entity.setAttribute("stuff");

//...

em.persist(entity);

// ...

// Here comes the query which should find above entity with attribute 'stuff'...

But. Whatever entity I create and persist in the unit test, is not findable from within the same test (or even method). I can successfully query the DB and find entities from there, but the newly persisted test cases are not there.

I guess I misunderstood some crucial thing about JPA the persistence context - I'd be glad if someone could enlighten me! :)

In case thats of importance, here is how the persistence.xml used by the tests looks like:

<persistence-unit name="persistenceUnitName" transaction-type="RESOURCE_LOCAL">

<provider>org.hibernate.ejb.HibernatePersistence</provider>

<!-- list of classes to manage -->

<properties>

<!-- driver and connection info, this works-->

</properties>

</persistence-unit>

网友答案:

You have EntityManager.getTransaction().begin() to start the transactiona and then rollback() to roll it back. Or maybe you can create a separate copied instance of the entire database just for testing? Just an idea.

分享给朋友:
您可能感兴趣的文章:
随机阅读: