How to find a value in a column that has unique values โ€‹โ€‹with EclipseLink?

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

But how do I find a value in a column that has only unique values โ€‹โ€‹and is not a primary key?

+6
source share
3 answers

For example, for example:

 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 one result, replace getResultList() with getSingleResult() :

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

Another way is to use the criteria API.

+5
source

You can use the 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 } 
+7
source

You can use Query, or JPQL, Criteria, or SQL.

Not sure if your problem is getting a cache similar to find (). EclipseLink 2.4 added cache indexes to index non-primary key fields and receive cache requests from JPQL or Criteria.

See, http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Caching/Indexes

Prior to 2.4, you can use in-memory queries to query the cache for non-identification fields.

+2
source

Source: https://habr.com/ru/post/918101/


All Articles