您可以EntityManager.find(Class entityClass, Object primaryKey)
使用主键查找特定行。
但是如何在只有唯一值且不是主键的列中找到一个值?
您可以EntityManager.find(Class entityClass, Object primaryKey)
使用主键查找特定行。
但是如何在只有唯一值且不是主键的列中找到一个值?
您可以将适当的 JPQL 与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
}
例如,像这样:
List<T> results = em.createQuery("SELECT t FROM TABLE t", T.class)
.getResultList();
带参数:
List<T> results = em.createQuery("SELECT t FROM TABLE t where t.value = :value1")
.setParameter("value1", "some value").getResultList();
对于单个结果替换getResultList()
为getSingleResult()
:
T entity = em.createQuery("SELECT t FROM TABLE t where t.uniqueKey = :value1")
.setParameter("value1", "KEY1").getSingleResult();
另一种方法是使用 Criteria API。
您可以使用查询,JPQL、Criteria 或 SQL。
不确定您是否关心获取类似于 find() 的缓存命中。在 EclipseLink 2.4 中添加了缓存索引,以允许您索引非主键字段并从 JPQL 或 Criteria 获取缓存命中。
见, http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Caching/Indexes
在 2.4 之前,您可以使用内存查询来查询非 id 字段的缓存。