在JPA中,查询为:
Query q = entityManager.createQuery("select o from Product o WHERE o.category = :value"); q.setParameter("category", category);
如何在JPA中将类别设置为任何类别?因此,如果传递了null类别,我将简单地忽略category参数,选择所有产品。
您必须在此处动态构建查询。使用HQL(这是一个简化的示例):
Map<String, Object> params = new HashMap<String, Object>(); StringBuffer hql = new StringBuffer("from Product p"); boolean first = true; if (category != null) { hql.append(first ? " where " : " and "); hql.append("p.category = :category"); params.put("category", category); } // And so on... Query query = session.createQuery(hql.toString()); Iterator<String> iter = params.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); Object value = params.get(name); query.setParameter(name, value); } List results = query.list()
但是,实际上,我的建议是在此处使用Criteria API:
Criteria criteria = session.createCriteria(Product.class); if (category != null) { criteria.add(Expression.eq("category", category); } // And so on... List results = criteria.list();
复杂的动态查询要简单得多。