CCM NG: Variante der findById Methode für fetchJoins erstellen erstellen (#2805)

git-svn-id: https://svn.libreccm.org/ccm/ccm_ng@5254 8810af33-2d31-482b-a856-94f89814c4df
ccm-docs
jensp 2018-02-07 14:01:52 +00:00
parent 2d37c5b2cb
commit 1a11da8b59
1 changed files with 31 additions and 4 deletions

View File

@ -28,6 +28,7 @@ import java.util.Optional;
import javax.inject.Inject;
import javax.persistence.EntityGraph;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
@ -127,8 +128,8 @@ public abstract class AbstractEntityRepository<K, E> implements Serializable {
/**
* Used by some methods to create queries using the JPA Criteria API.
*
* @return The name of the ID attribute/property for entities managed by
* a repository.
* @return The name of the ID attribute/property for entities managed by a
* repository.
*/
public abstract String getIdAttributeName();
@ -176,6 +177,32 @@ public abstract class AbstractEntityRepository<K, E> implements Serializable {
hints));
}
@Transactional(Transactional.TxType.REQUIRED)
public Optional<E> findById(final K entityId,
final String... fetchJoins) {
Objects.requireNonNull(entityId);
final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
final CriteriaQuery<E> criteriaQuery = builder
.createQuery(getEntityClass());
final Root<E> from = criteriaQuery.from(getEntityClass());
criteriaQuery.from(getEntityClass());
for (final String fetchJoin : fetchJoins) {
from.fetch(fetchJoin);
}
criteriaQuery
.where(builder.equal(from.get(getIdAttributeName()), entityId));
final TypedQuery<E> query = entityManager.createQuery(criteriaQuery);
try {
return Optional.of(query.getSingleResult());
} catch (NoResultException ex) {
return Optional.empty();
}
}
/**
* Finds all instances of the entity of the type this repository is
* responsible for.