您使用EntityManager.find(Class entityClass, Object primaryKey)
方法查找具有主键的特定行。
但是,如何在列中找到只有唯一值且不是主键的值?
答案 0 :(得分:13)
您可以在TypedQuery使用适当的JPQL。
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
}
答案 1 :(得分:7)
例如,像这样:
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。
答案 2 :(得分:3)
您可以使用查询,JPQL,Criteria或SQL。
不确定您是否在获取类似于find()的缓存命中。在EclipseLink 2.4中添加了缓存索引,以允许您索引非主键字段并从JPQL或Criteria获取缓存命中。
请参阅, http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Caching/Indexes
在2.4之前,您可以使用内存中查询来查询非id字段上的缓存。