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

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

问题描述

我是JPA的新手。

在JPA中,查询为:

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

如何在JPA中将类别设置为任何类别?因此,如果null类别通过,我会简单地忽略category参数,选择所有产品。

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中将类别设置为任何类别?因此,如果null类别通过,我简单地忽略category参数,选择所有产品。

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子句任何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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