Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 831
Rox Avatar asked Jun 14 '12 13:06

Rox


2 Answers

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.

like image 99
maksimov Avatar answered Oct 21 '22 12:10

maksimov


You can use appropriate JPQL with TypedQuery.

try {
    TypedQuery<Bean> tq = em.createQuery("from Bean WHERE column=?", Bean.class);
    Bean result = tq.setParameter(1, "uniqueKey").getSingleResult();
} catch(NoResultException noresult) {
    // if there is no result
} catch(NonUniqueResultException notUnique) {
    // if more than one result
}
like image 24
Pau Kiat Wee Avatar answered Oct 21 '22 12:10

Pau Kiat Wee