Home > Mobile >  Write query in CriteriaBuilder using Optional<T>
Write query in CriteriaBuilder using Optional<T>

Time:10-18

@Query(value = "select usd from UserDetail usd where usd.phoneNumber=:phoneNumber")
Optional<UserDetail> findByPhoneNumber(@Valid @Param("phoneNumber") String phoneNumber);

This is my JPQL query method and I am here using return type with Optional. I wonder how to write using CriteriaBuilder?

I wrote like this but I am getting an error.

@Override
public Optional<UserDetail> findByCreatedDate(String phoneNumber) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<UserDetail> cq = cb.createQuery(UserDetail.class);
    Root<UserDetail> root = cq.from(UserDetail.class);
    cq.where(cb.equal(root.get("phoneNumber"), phoneNumber))
      .orderBy(cb.desc(root.get("phoneNumber")));
    return em.createQuery(cq).getResultList().get(3);
}

CodePudding user response:

If the method return type is Optional that is what exactly you must return.

The line em.createQuery(cq).getResultList().get(3) returns only UserDetail so you need to wrap it to Optional.of:

@Override
public Optional<UserDetail> findByCreatedDate(String phoneNumber) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<UserDetail> cq = cb.createQuery(UserDetail.class);
    Root<UserDetail> root = cq.from(UserDetail.class);
    cq.where(cb.equal(root.get("phoneNumber"), phoneNumber))
      .orderBy(cb.desc(root.get("phoneNumber")));
    return Optional.of(em.createQuery(cq).getResultList().get(3));
}

By the way, are you sure the hardcoded .get(3) is what you want? If the list is empty or has less than 4 elements, it would throw a runtime exception.

CodePudding user response:

if a phone number is associated with only one person why are you trying to get a list ?

have a look to this :

@Override
        public Optional<UserDetail> findByCreatedDate(String phoneNumber) {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<UserDetail> cq = cb.createQuery(UserDetail.class);
            Root<UserDetail> root = cq.from(UserDetail.class);
            cq.where(cb.equal(root.get("phoneNumber"), phoneNumber)).orderBy(cb.desc(root.get("phoneNumber")));
            UserDetail ud = em.createQuery(cq).getSingleResult();
            return ud == null ? Optional.empty() : Optional.of(ud)
    
        }

Regards,

  • Related