1

私はEclipselink JPAを初めて使用します。多数の検索パラメーターを含む一連の複雑な検索クエリがあり、一部のパラメーターはオプションです。名前付きクエリでオプションのパラメータを指定する方法はありますか? 以下のアプローチは効率的な方法ですか?select o from Product o WHERE :value is null or o.category = :value'

4

1 に答える 1

5

あなたのアプローチはおそらくうまくいくでしょうが、私は通常、同様の状況でCriteria APIを使用します。たとえば、パラメータが提供されている場合、条件付きで条件クエリに述語を追加できます。

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Product> cq = cb.createQuery(Product.class);
Root<Product> e = cq.from(Product.class);

List<Predicate> predicates = new ArrayList<Predicate>();
if (categoryValue != null)
  predicates.add(cb.equal(e.get("category"), categoryValue));
if (someOtherValue != null)
  predicates.add(cb.equal(e.get("someField"), someOtherValue));

// AND all of the predicates together:
if (!predicates.isEmpty())
  cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));

List<Product> products = em.createQuery(cq).getResultList();

これは見苦しい例ですがCriteriaBuilder、API に慣れると非常に強力です。

于 2013-06-06T16:58:27.487 に答える