finding an entity by its unique attribute value.


    public static <T extends BaseEntity, Y> Optional<T> findByUniqueAttribute(
            final EntityManager entityManager,
            final Class<T> entityClass,
            final Supplier<SingularAttribute<? super T, Y>> attributeSupplier,
            final Supplier<? extends Y> valueSupplier) {
        final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        final CriteriaQuery<T> criteria = builder.createQuery(entityClass);
        final Root<T> root = criteria.from(entityClass);
        criteria.select(root);
        criteria.where(builder.equal(root.get(
                attributeSupplier.get()), valueSupplier.get()));
        try {
            return Optional.of(
                    entityManager.createQuery(criteria).getSingleResult());
        } catch (final NoResultException nre) {
            return Optional.empty();
        }
    }
    public static <T extends BaseEntity, Y> Optional<T> findByUniqueAttribute2(
            @NotNull final EntityManager entityManager,
            @NotNull final Class<T> entityClass,
            @NotNull final Function<ManagedType<T>, SingularAttribute<? super T, Y>> attributeSupplier,
            @NotNull final Supplier<? extends Y> valueSupplier) {
        final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        final CriteriaQuery<T> criteria = builder.createQuery(entityClass);
        final Root<T> root = criteria.from(entityClass);
        criteria.select(root);
        criteria.where(builder.equal(
                root.get(attributeSupplier.apply(
                        entityManager.getMetamodel().entity(entityClass))),
                valueSupplier.get()));
        try {
            return Optional.of(
                    entityManager.createQuery(criteria).getSingleResult());
        } catch (final NoResultException nre) {
            return Optional.empty();
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s