JPA where 子句 any [英] JPA where clause any

查看:32
本文介绍了JPA where 子句 any的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JPA 中,查询是:

In JPA, the query is:

Query q = entityManager.createQuery("select o from Product o WHERE o.category = :value");
q.setParameter("category", category);

如何将类别设置为 JPA 中的任何类别?所以如果空分类通过,我简单的忽略分类参数,选择所有产品.

How can I set category to any category in JPA? So if the null category passed, I simple ignore the category parameter, select all products.

推荐答案

如何将类别设置为 JPA 中的任何类别?所以如果空分类通过,我简单的忽略分类参数,选择所有产品.

How can I set category to any category in JPA? So if the null category passed, I simple ignore the category parameter, select all products.

您必须在此处动态构建查询.使用 HQL(这是一个简化示例):

You'll have to build the query dynamically here. With HQL (this is a simplified example):

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:

But, actually, my recommendation would be to use the Criteria API here:

Criteria criteria = session.createCriteria(Product.class);
if (category != null) {
    criteria.add(Expression.eq("category", category);
}
// And so on...
List results = criteria.list();

对于复杂的动态查询要简单得多.

Much simpler for complicated dynamic queries.

这篇关于JPA where 子句 any的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆