这是我要执行的代码:
Query query = getSession().createQuery("select count(*),uv.voter.gender from UserVoter uv where " +
" uv.voter.age between "+startAge+" and "+endAge+" and uv.hamlet.hamletId = :hamletId group by uv .voter.gender ") ;
//query.setParameter("publicationDateId",publicationDateId);
query.setParameter("hamletId", hamletId);
return query.list();
以下是开始和结束参数的情况:
18-25
25-35
35-45
对于这 3 种情况,我必须运行查询 3 次。以上三种情况,我想在一次查询中得到结果。我对 new map()
有一个想法,但我该怎么做呢?
输出应该映射到一对输入参数,例如:
18-25,55,男18-25,56,女25-35,44,男..
在mysql中我实现了这个
select concat(18,'to',25),count( v.voter_id),v.gender from voter v join user_voter u on v.voter_id = u.voter_id
where v.age between 18 and 25 and u.hamlet_id=10 group by v.gender
union
select concat(26,'to',35),count( v.voter_id),v.gender from voter v join user_voter u on v.voter_id = u.voter_id
where v.age between 26 and 35 and u.hamlet_id=10 group by v.gender
union
select concat(36,'to',50),count( v.voter_id),v.gender from voter v join user_voter u on v.voter_id = u.voter_id
where v.age between 36 and 50 and u.hamlet_id=10 group by v.gender
union
select concat(51,'to',200),count( v.voter_id),v.gender from voter v join user_voter u on v.voter_id = u.voter_id
where v.age between 51 and 200 and u.hamlet_id=10 group by v.gender;
但是如何在不使用原生 sql 的情况下在 hibernate 中获得这种效果呢?
最佳答案
首先,您还应该为 startAge 和 endAge 使用参数。
然后你可以在你的字符串中生成所需的其他条件,用于在你的案例上使用 for 循环进行查询,这会给你类似的东西:
(uv.voter.age between :startAge0 and :endAge0) or (uv.voter.age between :startAge1 and :endAge1) ...
您可以轻松生成以下字符串,然后使用 namedParameters 添加参数。 如果您不喜欢这种情况下的定位参数,您可以看看(使用'?'然后使用索引设置参数。
关于java - 如何将 List<Object[]> 设置为 HQL 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15090682/