Take the 2-minute tour ×

In JPA (Hibernate), when we automatically generate the ID field, it is assumed that the user has no knowledge about this key. So, when obtaining the entity, user would query based on some field other than ID. How do we obtain the entity in that case (since em.find() cannot be used).

I understand we can use a query and filter the results later. But, is there a more direct way (because this is a very common problem as I understand).

share|improve this question
add comment

3 Answers

It is not a "problem" as you stated it.

Hibernate has the built-in find(), but you have to build your own query in order to get a particular object. I recommend using Hibernate's Criteria :

Criteria criteria = session.createCriteria(YourClass.class);
YourObject yourObject = criteria.add(Restrictions.eq("yourField", yourFieldValue))

This will create a criteria on your current class, adding the restriction that the column "yourField" is equal to the value yourFieldValue. uniqueResult() tells it to bring a unique result. If more objects match, you should retrive a list.

List<YourObject> list = criteria.add(Restrictions.eq("yourField", yourFieldValue)).list();

If you have any further questions, please feel free to ask. Hope this helps.

share|improve this answer
Is this Hibernate specific? Can I use this with JPA as well? –  Venkatesh Feb 20 '13 at 10:19
Just read that this can work with JPA as well. –  Venkatesh Feb 20 '13 at 10:35
Criteria is Hibernate specific because it comes from org.hibernate package. –  Raul Rene Feb 20 '13 at 12:14
add comment

Have a look at:

share|improve this answer
add comment

Write a custom method like this below

public Object findByYourField(Class entityClass, String yourFieldValue)
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery(entityClass);
    Root<Object> root = criteriaQuery.from(entityClass);

    ParameterExpression<String> params = criteriaBuilder.parameter(String.class);
    criteriaQuery.where(criteriaBuilder.equal(root.get("yourField", params));

    TypedQuery<Object> query = entityManager.createQuery(criteriaQuery);
    query.setParameter(params, yourFieldValue);

    List<Object> queryResult = query.getResultList();

    Object returnObject = null;

    if (CollectionUtils.isNotEmpty(queryResult))
        returnObject = queryList.get(0);

    return returnObject;
share|improve this answer
add comment

Your Answer


