Advertisement
Guest User

EntityGetter

a guest
Feb 12th, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.40 KB | None | 0 0
  1. package metubeV2.repository.util;
  2.  
  3. import javax.persistence.EntityManager;
  4. import javax.persistence.NoResultException;
  5. import javax.persistence.criteria.CriteriaBuilder;
  6. import javax.persistence.criteria.CriteriaQuery;
  7. import javax.persistence.criteria.Root;
  8. import java.util.Optional;
  9.  
  10. /**
  11.  * Created by IntelliJ IDEA.
  12.  * User: LAPD
  13.  * Date: 7.2.2019 г.
  14.  * Time: 10:07 ч.
  15.  */
  16. public class EntityGetter<T> {
  17.  
  18.      public static<T> Optional<?> getEntityByParameter(String name,
  19.                                                    String parameterName,
  20.                                                    EntityManager entityManager,
  21.                                                    Class<T> aClass) {
  22.         CriteriaBuilder criteriaBuilder = entityManager
  23.                 .getCriteriaBuilder();
  24.         CriteriaQuery<T> criteriaQuery = (CriteriaQuery<T>) criteriaBuilder
  25.                 .createQuery(aClass.getClass());
  26.         Root<T> root = (Root<T>) criteriaQuery.from(aClass.getClass());
  27.  
  28.         criteriaQuery.select(root)
  29.                 .where(criteriaBuilder
  30.                         .equal(root.get(parameterName), name));
  31.  
  32.         try {
  33.             return Optional.ofNullable(entityManager
  34.                     .createQuery(criteriaQuery)
  35.                     .getSingleResult());
  36.  
  37.         } catch (NoResultException ignored) {
  38.             return Optional.empty();
  39.         }
  40.     }
  41.  
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement