Last active
April 8, 2020 22:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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