Query using CriteriaQuery and EntityManager (Hibernate)

How to create a query using CriteriaQuery and EntityManager for this SQL query:

SELECT * FROM user WHERE user.login = '?' and user.password = '?' 

      

I am doing my best:

        final CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
        final CriteriaQuery<User> criteriaQuery = criteriaBuilder.createQuery(User.class);
        Root<User> root = criteriaQuery.from(User.class);
        criteriaQuery.select(root);
        criteriaQuery.where(criteriaBuilder.gt(root.get("login"), userLogin));
        return getEntityManager().createQuery(criteriaQuery).getResultList().get(0);

      

+3


source to share


2 answers


Your code looks like it is on the right track, except that it only has one condition WHERE

, which is inconsistent with your raw SQL, which has two conditions.

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> q = cb.createQuery(User.class);
Root<User> c = q.from(User.class);
q.select(c);
ParameterExpression<String> p1 = cb.parameter(String.class);
ParameterExpression<String> p2 = cb.parameter(String.class);
q.where(
    cb.equal(c.get("login"), p1),
    cb.equal(c.get("password"), p2)
);
return em.createQuery(q).getResultList().get(0);

      



As a basic real-life note, you usually won't store raw user passwords in your database. Rather, you are storing a salted and encrypted password. So hopefully your actual program doesn't store raw passwords.

0


source


In the end, this worked for me:



    entityManager.getTransaction().begin();

    CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
    Root<Profile> fromRoot = criteriaQuery.from(Profile.class);
    criteriaQuery.select(fromRoot);

    criteriaQuery.where(criteriaBuilder.equal(fromRoot.get("userName"), username),
                        criteriaBuilder.equal(fromRoot.get("password"), password));

    List<Object> resultList = entityManager.createQuery(criteriaQuery).getResultList();
    Profile dbProfile = null;
    if (resultList.isEmpty()) {
        // Handle Error
    } else {
        dbProfile = (Profile) resultList.get(0);
    }

    entityManager.getTransaction().commit();

      

0


source







All Articles