Ghost
Ghost

Reputation: 113

How to clean all entities from EntityManager?

I'm working on a JavaEE application with EJB and JPA.

I'm doing some tests and entities are persisting. Although, I'd like to remove entities between those tests. I tried to use the method EntityManager.clear() but this doesn't work. When I try to consult one of the old entities, it is still on the EntityManager.

How can I solve this problem?

Upvotes: 0

Views: 2599

Answers (1)

uaiHebert
uaiHebert

Reputation: 1912

Invoking EntityManager.clear() will not remove the entities, because they are persisted in the database. You could close your entity manager factory and open again:

@Before
public void beforeTest() {
    entitManagerFactory.close()
    entitManagerFactory = // new EntityManagerFactory
}

The problem with this approach is that create an EntityManager may slow down the tests process.

What you could do instead is:

1) You could delete all entities before the test:

@Before
public void beforeTest() {
    // execute a query like delete from Person p
}

2) You could use a new ID/values for every test:

@Test
public void test1() {
    Person person = PersonTestUtil.createPerson("11111");
}

@Test
public void test2() {
    Person person = PersonTestUtil.createPerson("22222");
}

Upvotes: 3

Related Questions