使用动态where子句hibernate [英] Using dynamic where clause hibernate

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

问题描述

我试图建立一个查询,其中一些字段是基于用户选择从客户端发送的。
我打算创建一个基于用户选择的动态查询。尽管我可以简单地用一些java代码和数据库来做到这一点,但让hibernate为我启动该查询并返回结果。

I am trying to build a query where some of the fields are being sent from the client side based on user selection. I am planing to create a dynamic query based on the selection by user.Though i can do it simply with some java code and den let hibernate to fire that Query for me and return the result.

我的问题是,我可以使用hibernate机制中的构建做同样的事情。
例如我会得到一张地图,说:

My question is, can i do same using build in hibernate mechanism. e.g i will get a map say

(cond1:a,cond2:b,cond3:c)

唯一的区别是map可以包含的值的数量,并基于该值我想创建一个查询
就像

only difference is the number of values map can contain and based on that i want to create a query like

select * from demo where cond1='a' and cond2='b' and cond3='c'; and may be 
select * from demo where cond1='a' and cond2='b'; when map has only 2 values

预先致谢

Thanks in advance

推荐答案

使用标准

This shouldn't be a problem by using criteria.

CriteriaBuilder queryBuilder = em.getCriteriaBuilder();
CriteriaQuery query = queryBuilder.createQuery();
Root<Demo> demo = query.from(Demo.class);

Iterator it = map.entrySet().iterator();
Map.Entry wherePair = (Map.Entry)it.next();  // This is retrieved for creating the where clause
query.where(wherePair.getKey() + "=" + wherePair.getValue());

while (it.hasNext()) {
   Map.Entry pairs = (Map.Entry)it.next();
   query.and(" " + pairs.getKey() + "=" + pairs.getValue());
}

我不能保证它会被编译,但那会是主意。

I can't guarantee it will compile, but that'd be the idea.

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

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