14

您可以EntityManager.find(Class entityClass, Object primaryKey)使用主键查找特定行。

但是如何在只有唯一值且不是主键的列中找到一个值?

4

3 回答 3

16

您可以将适当的 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
}
于 2012-06-14T13:50:33.750 回答
12

例如,像这样:

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。

于 2012-06-14T13:45:04.333 回答
2

您可以使用查询,JPQL、Criteria 或 SQL。

不确定您是否关心获取类似于 find() 的缓存命中。在 EclipseLink 2.4 中添加了缓存索引,以允许您索引非主键字段并从 JPQL 或 Criteria 获取缓存命中。

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

在 2.4 之前,您可以使用内存查询来查询非 id 字段的缓存。

于 2012-06-14T14:26:02.160 回答