Created
September 30, 2021 07:37
-
-
Save madgrk/797df26e3ac5bc3e3dc618767422c94d to your computer and use it in GitHub Desktop.
JPA SingularAttribute on 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
public abstract class GenericDAOImpl<T extends DomainObject, T2 extends DomainObject> implements GenericDAO<T, T2> { | |
private Class<T> type; | |
@PersistenceContext | |
protected EntityManager entityManager; | |
public GenericDAOImpl(Class<T> type) { | |
super(); | |
this.type = type; | |
} | |
... save and delete classes go here | |
@Override | |
public List<T> findAll(T2 where) { | |
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); | |
CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(type); | |
Root<T> rootQuery = criteriaQuery.from(type); | |
if (where != null) { | |
EntityType<T> entity = entityManager.getMetamodel().entity(type); | |
SingularAttribute<? super T, ?> attribute = null; | |
for (SingularAttribute<? super T, ?> singleAttribute: entity.getSingularAttributes()) { | |
// loop through all attributes that match this class | |
if (singleAttribute.getJavaType().equals(where.getClass())) { | |
// winner! | |
attribute = singleAttribute; | |
break; | |
} | |
} | |
// where t.object = object.getID() | |
criteriaQuery.where(criteriaBuilder.equal(rootQuery.get(attribute), where)); | |
} | |
criteriaQuery.select(rootQuery); | |
TypedQuery<T> query = entityManager.createQuery(criteriaQuery); | |
// need this to make sure we have a clean list? | |
// entityManager.clear(); | |
return query.getResultList(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment