我遇到了一个问题,我花了很长时间试图搞清楚。
我是hibernate的新手,我的数据看起来像。
我想编写一个返回此数据的查询,看起来像这样。
如果只使用一个理想的SQL语句就可以完成,因为我仍然非常不熟悉hibernate的一些更好的功能。我尝试了很多东西,我认为我可以用Unions来做,但不幸的是hibernate不支持工会。
任何建议表示赞赏。如果建议是一种更加以hibernate为导向的方法,那么尽可能多的细节将是值得赞赏的。
UPDATE://
来自ANGELO的评论,我能够使用以下内容实现这一点:
String newQuery = "";
List<?> list = null;
Query quer = null;
Session session = null;
session = HibernateUtilities.getSessionFactory().openSession();
newQuery =
"SELECT DISTINCT o.APPLICATION,(SELECT DATA FROM " + dataTable + " gsm WHERE gsm.APPLICATION = o.APPLICATION AND gsm.NETWORK_TYPE = 'GSM Usage') AS gsm, (SELECT DATA FROM " + dataTable + " wifi WHERE wifi.APPLICATION = o.APPLICATION AND wifi.NETWORK_TYPE = 'Wi-Fi Usage') AS wifi, (SELECT DATA FROM " + dataTable + " roam WHERE roam.APPLICATION = o.APPLICATION AND roam.NETWORK_TYPE = 'ROAMING Usage') AS roaming FROM " + dataTable + " o";
quer = session.createQuery(newQuery);
list = quer.list();
session.close();
答案 0 :(得分:1)
你可以使用子选择(在SQL中,Marko在评论中说它在Hibernate中不起作用。)
SELECT DISTINCT o.application,
(SELECT sum(DATA) FROM tbl gsm WHERE gsm.application = o.application AND gsm.network_type = 'GSM') AS gsm,
(SELECT sum(DATA) FROM tbl wifi WHERE wifi.application = o.application AND wifi.network_type = 'WIFI') AS wifi,
(SELECT sum(DATA) FROM tbl roam WHERE roam.application = o.application AND roam.network_type = 'ROAMING') AS roaming
FROM tbl o
(请注意,我假设您的表名为tbl
)