You have to understand the following, the cache is tied to the Persistencecontext that is created when you create an Entitymanager.
You can easily use Junit with Entitymanager to test your DAO. What you should do is:
- Add HSQLDB as dependency or some other database in memory
- Having persistence.xml only for the test, in which case, simply add it inside a test directory, in the case of Maven, that automatically this context change would be made.
Create a static Entitymanagerfactory:
private Static Entitymanagerfactory entityManagerFactory;
Create a annotated static method with @Beforeclass that will create Entitymanagerfactory:
@Beforeclass
public Static void createPersistenceUnit() {
entityManagerFactory = Persistence.createEntityManagerFactory("PU")
}
Create a annotated static method with @Afterclass to kill Entitymanagerfactory:
@Afterclass
public Static void closePersistenceUnit() {
entityManagerFactory.close();
}
Create an annotated method with @Before to start Entitymanager each test:
@Before
public void beforeTest() {
entityManager = getEntityManagerFactory(). createEntityManager();
}
Create a method with @After to finish Entitymanager after each test:
@After
public void finishTest() {
entityManager.close();
}
This way you will have an Entitymanager for each test and your first level cache will be no problem.
This post is a little old, but talks about it: http://uaihebert.com/tdd-com-hsqldb-jpa-e-hibernate/
This is the appropriate strategy for most situations.
– utluiz