I’m working with a MySQL database that has several tables and views. These views are basically joins between different tables. I created RESTful web services using these database objects and deployed them on a Tomcat server.
The problem is that there’s an external application that updates the database tables independently. When I query the database directly, I can see the updated data. But when I fetch data through my REST services, the old values are still returned. I think this happens because JPA caches the entity data and doesn’t know about the external changes.
I tried to solve this by adding some methods to my base facade class:
public abstract class BaseFacade<T> {
private Class<T> entityType;
private String entityTypeName;
private static boolean needsRefresh = true;
public static void triggerRefresh() { needsRefresh = true; }
public BaseFacade(Class<T> entityType) {
this.entityType = entityType;
this.entityTypeName = entityType.getSimpleName();
}
private void performRefresh() {
if (needsRefresh) {
EntityManager manager = getEntityManager();
manager.flush();
for (EntityType<?> type : manager.getMetamodel().getEntities()) {
if (type.getName().contains(entityTypeName)) {
try {
manager.refresh(type);
// success logging
}
catch (IllegalArgumentException ex) {
// error logging - usually says entity is not managed
}
}
}
needsRefresh = false;
}
}
}
I call performRefresh() from my finder methods, but I keep getting IllegalArgumentException saying the entity is not managed.
How can I properly refresh my JPA entities to reflect the latest database changes made by external processes?