hibernate使用原生sql查询时返回的字段不能重命名
例如使用如下sql查询时报错
sql = "SELECT t.type_name as `name`,SUM(o.circulation) FROM "
+ " t_info_product o "
+ " LEFT JOIN t_info_type t ON o.media_type = t.type_id"
+ " where o.del_state= 0 "
+ " GROUP BY o.media_type";
因为hibernate会自动给hibernate自动取别名
后面放弃了对type_name取别名,对SUM(o.circulation)列取别名竟然成功了,这也是预料之中的,查出来的字段太复杂,必然存在可重命名功能
下面是正确的
sql = "SELECT t.type_name ,SUM(o.circulation) as `sum` FROM "
+ " t_info_product o "
+ " LEFT JOIN t_info_type t ON o.media_type = t.type_id"
+ " where o.del_state= 0 "
+ " GROUP BY o.media_type";
由此便可以想到对 t.type_name重名的的方法了,需要一个sql函数
CONCAT()对就是他
sql = "SELECT CONCAT(t.type_name) as 'name' ,SUM(o.circulation) as `sum` FROM "
+ " t_info_product o "
+ " LEFT JOIN t_info_type t ON o.media_type = t.type_id"
+ " where o.del_state= 0 "
+ " GROUP BY o.media_type";
设置数据类型为List
public List<Map<String, Object>> listMap(final String sql) {
return getHibernateTemplate().executeFind(new HibernateCallback() {
public List<T> doInHibernate(Session session) // 此处的session可以不用管,自动获得
throws HibernateException, SQLException {
Query query = session.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); //设置返回类型
// query.setCacheable(true); //使用缓存
return query.list();
}
});
}
查出来的数据可以直接转json传到前台