Hibernate统计一个字段的多个可能值_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Hibernate统计一个字段的多个可能值

Hibernate统计一个字段的多个可能值

 2015/4/14 18:30:20  逆天子军少  程序员俱乐部  我要评论(0)
  • 摘要:问题:针对一张表的一个字段,想要统计其出现的不同值的次数,并封装为对象集合返回。坑点:1.hql语句中sum()返回一个long值,所以如果定义的对象实体类字段为int型,则会报错。2.要想日期直接用<>比较,必须保持日期格式,例如2014/01/01代码:Queryquery=this.getSession().createQuery("selecthzmydCkpjsjJgmc,count(hzmydCkpjsjPjjg)astotalCommentCounts,"+"sum
  • 标签:一个 hibernate
问题:针对一张表的一个字段,想要统计其出现的不同值的次数,并封装为对象集合返回。
坑点
1.hql语句中sum()返回一个long值,所以如果定义的对象实体类字段为int型,则会报错。
2.要想日期直接用<>比较,必须保持日期格式,例如2014/01/01
代码
class="java">
		 Query query = this
		 .getSession()
		 .createQuery(
		 "select hzmydCkpjsjJgmc,count(hzmydCkpjsjPjjg) as totalCommentCounts,"
		 +
		 "sum(case when hzmydCkpjsjPjjg='非常满意' then 1 else 0 end) as muchSatiCounts,"
		 +
		 "sum(case when hzmydCkpjsjPjjg='满意' then 1 else 0 end) as manuSatiCounts,"
		 +
		 "sum(case when hzmydCkpjsjPjjg='未评' then 1 else 0 end) as autoSatiCounts,"
		 +
		 "sum(case when hzmydCkpjsjPjjg='基本满意' then 1 else 0 end) as basicSatiCounts,"
		 +
		 "sum(case when hzmydCkpjsjPjjg='不满意' then 1 else 0 end) as notSatiCounts "
		 + " from HzmydCkpjsj "
		 + "where hzmydCkpjsjJlrq>=:startTime and hzmydCkpjsjJlrq<=:endTime "
		 + "group by hzmydCkpjsjJgmc")
		 .setParameter("startTime", startTime)
		 .setParameter("endTime", endTime);
		 List<Object[]> list = query.list();
		 List<GroupHzmydCkpjsjByKs> resultList = new
		 ArrayList<GroupHzmydCkpjsjByKs>();
		 for (Object[] obj : list) {
		 GroupHzmydCkpjsjByKs gByKs = new GroupHzmydCkpjsjByKs();
		 gByKs.setTotalCommentCounts((Long) obj[1]);
		 gByKs.setMuchSatiCounts((Long) obj[2]);
		 gByKs.setManuSatiCounts((Long) obj[3]);
		 gByKs.setAutoSatiCounts((Long) obj[4]);
		 gByKs.setBasicSatiCounts((Long) obj[5]);
		 gByKs.setNotSatiCounts((Long) obj[6]);
		 gByKs.setHzmydCkpjsjJgmc(obj[0].toString());
		 resultList.add(gByKs);
		 }
return resultList;

当然,还有个简单的:
	Query query = this
				.getSession()
				.createQuery(
						"select new com.fxfk.entity.GroupHzmydCkpjsjByKs(hzmydCkpjsjJgmc,count(hzmydCkpjsjPjjg) as totalCommentCounts,"
								+ "sum(case when hzmydCkpjsjPjjg='非常满意' then 1 else 0 end) as muchSatiCounts,"
								+ "sum(case when hzmydCkpjsjPjjg='满意' then 1 else 0 end) as manuSatiCounts,"
								+ "sum(case when hzmydCkpjsjPjjg='未评' then 1 else 0 end) as autoSatiCounts,"
								+ "sum(case when hzmydCkpjsjPjjg='基本满意' then 1 else 0 end) as basicSatiCounts,"
								+ "sum(case when hzmydCkpjsjPjjg='不满意' then 1 else 0 end) as notSatiCounts) "
								+ " from HzmydCkpjsj "
								+ "where hzmydCkpjsjJlrq>=:startTime and hzmydCkpjsjJlrq<=:endTime "
								+ "group by hzmydCkpjsjJgmc")
				.setParameter("startTime", startTime)
				.setParameter("endTime", endTime);
		List<GroupHzmydCkpjsjByKs> resultList = query.list();
		return resultList;
发表评论
用户名: 匿名