studentST
studentST

Reputation: 307

Query with using CriteriaQuery and EntityManager(Hibernate)

How create query with using CriteriaQuery and EntityManager for this SQL query:

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

I try so:

        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);

Upvotes: 4

Views: 7811

Answers (2)

ASH
ASH

Reputation: 1058

This worked for me in the end was this:

    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();

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522712

Your code looks like it's on the right track, except that it only has one WHERE condition, which does not agree with your raw SQL query, 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 side note, in real life you would typically not be storing raw user passwords in your database. Rather, you be storing a salted and encrypted password. So hopefully your actual program is not storing raw passwords.

Upvotes: 1

Related Questions