Skip to content

@dewind /RefreshEntityInterceptor.java
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
public class RefreshEntityInterceptor implements MethodInterceptor {
@Inject
private Provider<EntityManager> entityManagerProvider;
@Inject
protected Logger logger;
@SuppressWarnings("unchecked")
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
try {
Object result = methodInvocation.proceed();
List<Object> entities;
if(result == null) {
return result;
}
if(!Collection.class.isAssignableFrom(result.getClass())) {
entities = new ArrayList<Object>();
entities.add(result);
} else {
entities = new ArrayList<Object>((Collection)result);
}
EntityManager entityManager = entityManagerProvider.get();
for (Object entity : entities) {
if(entityManager.contains(entity)) {
clearAllCollections(entity);
entityManager.refresh(entity);
}
}
return result;
} catch (Throwable throwable) {
logger.error("Failed to refresh entity", throwable);
throw throwable;
}
}
private void clearAllCollections(Object entity) {
clearAllCollectionsOnMethods(entity);
clearAllCollectionsOnFields(entity);
}
private void clearAllCollectionsOnFields(Object entity) {
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field : fields) {
if(field.isAnnotationPresent(OneToMany.class)) {
try {
field.setAccessible(true);
Object result = field.get(entity);
if(result != null) {
Collection collection = (Collection) result;
collection.clear();
}
} catch (IllegalAccessException e) {
logger.error("Could not clear entity collection before refreshing", e);
}
}
}
}
private void clearAllCollectionsOnMethods(Object entity) {
Method[] methods = entity.getClass().getMethods();
for (Method method : methods) {
if(method.isAnnotationPresent(OneToMany.class)) {
try {
method.setAccessible(true);
Object result = method.invoke(entity);
Collection collection = (Collection) result;
if(result != null) {
collection.clear();
}
} catch (IllegalAccessException e) {
logger.error("Could not clear entity collection before refreshing", e);
} catch (InvocationTargetException e) {
logger.error("Could not clear entity collection before refreshing", e);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.