Search code examples
javasqljpaeclipselink

How do I find a value in a column that just have unique values with EclipseLink?


You have the EntityManager.find(Class entityClass, Object primaryKey) method to find a specific row with a primary key.

But how do I find a value in a column that just have unique values and is not a primary key?


Solution

  • For example, like this:

    List<T> results = em.createQuery("SELECT t FROM TABLE t", T.class)
                            .getResultList();
    

    With parameters:

    List<T> results = em.createQuery("SELECT t FROM TABLE t where t.value = :value1")
                            .setParameter("value1", "some value").getResultList();
    

    For single result replace getResultList() with getSingleResult():

    T entity = em.createQuery("SELECT t FROM TABLE t where t.uniqueKey = :value1")
                     .setParameter("value1", "KEY1").getSingleResult();
    

    One other way is to use Criteria API.