Reputation: 1089
I am having issues with JPA keeping old data in cache and had tried the solutions I could find but it keeps popping up!
Anyway, I initially reused one Entity Manager instance for efficiency. When I first encountered the described problem, I changed my code so that a new Entity Manager is made per transaction:
/** This method is called every time a transaction is made. */
public static EntityManager createFreshEntityManager() {
try {
return Persistence.createEntityManagerFactory(puName)
.createEntityManager();
}
catch (Exception e) {
logStuff(e);
return null;
}
}
However, this does NOT resolve the issue.
When I truncated a table using JDBC and reset the primary keys, I often notice that certain newly-created objects have old variable values. One suspicion I have is that resetting the primary key can be a culprit, but then again, I already have a new Entity Manager per transaction, so that shouldn't matter at all.
I am pretty confident that it is not an issue with my code, since DB entities are never stored in my application outside of function scope and are always queried directly from DB when needed.
I've also read about using EntityManager.clear(), but I'd prefer not to do something as brutal as that, as it can mess up multi-threaded programs.
I've thought of doing a TRUNCATE using JPA instead of JDBC by getting all objects at once and then delete them one by one manually, but that's just inefficient... But then again, it wouldn't be a bottleneck. Not sure if that'd make a difference w.r.t. doing it using JDBC though.
Upvotes: 1
Views: 575
Reputation: 22692
I don't see any reason to create a new EntityManager for every transaction.
You should be able to inject your EntityManager using @PersistenceContext.
It might look something like this:
@Stateless
class SomeSessionBean implements SomeSessionBeanLocal {
@PersistenceContext(unitName = "somePuName")
private EntityManager em;
public Customer findCustomerById(Long someId) {
return em.find(Customer.class, someId);
}
}
Using Annotations for dependency injection is one of the greatest things about EJB 3!
The probable source of your problem:
If you're modifying values in the database while your JavaEE web application is running, the changes aren't likely to be detected by your EJBs immediately. Your peristence layer is probably using a cache.
You probably want to restart your webapp after making database changes "externally".
Upvotes: 2