发表于: 2017-03-31 21:26:23
4 1291
今天完成的事情:完成数据汇总统计表格查询
明天计划的事情:完成实习任务
遇到的问题:原生sql 查 日期报错
String sql = "select count('f_modulename') as visit_count, f_modulename ,f_username from TBTKY_VISIT_LOG_ROLE_V t " +
"where f_username='"+ fusername +"'" +
"and f_createtime>=(to_date('"+ startTime+" ','yyyy/mm/dd HH24:MI:SS')) " +
"and f_createtime<=(to_date('"+endTime+"','yyyy/mm/dd HH24:MI:SS')) " +
"group by f_modulename,f_username";
如果不转日期类型,就会报日期错误
2、hibernate标准查询分组后,分组字段不能出现到where中
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(TbtkyVisitLogRoleV.class);
if( !queryMap.get("frolename").equals("全部") && queryMap.get("frolename") != null && queryMap.get("frolename") != "") {
criteria.add(Restrictions.eq("frolename", queryMap.get("frolename")));
}
criteria.setProjection(
Projections.projectionList()
.add( Projections.property("fusername"), "fusername") //为fusername属性指定一个别名,根据别名进行其他操作。map形式返回,所以要设置别名,作为key
.add( Projections.property("frname"),"frname")
.add( Projections.count("vid"),"visitCount") // 统计一个属性在结果中出现的次数。vid可以当做行数,相当于count(*)
.add( Projections.groupProperty("fusername")) //按fuserame属性分组
.add( Projections.groupProperty("frname"))
);
criteria.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP); //用map形式返回,必须要有key:value
if(startTime!=null) //查询制定时间之后的记录
criteria.add(Restrictions.ge("fcreatetime",startTime));
if(endTime!=null) //查询指定时间之前的记录
criteria.add(Restrictions.le("fcreatetime",endTime)); //where中不能出现group字段
List moduleList = null; //eg:{findexRegionCode=xiaoli, visitCount=3}
try {
moduleList = criteria.list();
} catch (Exception e) {
this.logger.error(e.getMessage());
}
return moduleList;
等效:
select this_.f_username as y0_, this_.f_rname as y1_, count(this_.vid) as y2_, this_.f_username as y3_, this_.f_rname as y4_ from TBTKY_VISIT_LOG_ROLE_V this_ where this_.f_createtime>=? and this_.f_createtime<=? group by this_.f_username, this_.f_rname
收获:用sql从数据库取数据,其实hibernate也是在控制台拼的原生sql。hibernate防止了sql注入
评论