Skip to content

Instantly share code, notes, and snippets.

@lekant
Last active April 8, 2020 22:35
Show Gist options
  • Save lekant/21eab41e3a863727f5be to your computer and use it in GitHub Desktop.
Save lekant/21eab41e3a863727f5be to your computer and use it in GitHub Desktop.
How to get an already existing entity root in a JPA criteria query
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.Iterator;
import java.util.Set;
/**
* Created by qlehenaff on 12/10/15.
*/
public class QueryEntitiesHelper<R> {
public Root<R> getExistingRoot(CriteriaQuery<?> query, Class<R> clazz) {
Root<R> root = null;
final Set<Root<?>> roots = query.getRoots();
if (!roots.isEmpty()) {
final Iterator<Root<?>> iterator = roots.iterator();
while (iterator.hasNext()) {
final Root<?> next = iterator.next();
if (next.getModel().getName().equals(clazz.getSimpleName())) {
root = (Root<R>) next;
break;
}
}
if(root == null) {
root = query.from(clazz);
}
} else {
root = query.from(clazz);
}
return root;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment