項目中遇到的HQL查詢問題,項目遇到HQL問題

來源:互聯網
上載者:User

項目中遇到的HQL查詢問題,項目遇到HQL問題

問題描述:
目的:想要查詢出所有最新版本的組件
說明:組件:版本 =1:n關係 ,如果這個組件只有一個版本也要能夠查出來。

項目中使用的是記憶體資料庫,無法看到表結構,這裡的例子僅僅用於類比。
也即是:

select component from Component component where component.owner=:userId andcomponent.componentId.version.versionString in (select Max(c.componentId.version.versionString) from Component c where component.owner=:userId  group by c.componentId.name )

不足:發現對於同一個組件,它的不同版本都能出現,這個bug我沒發現,後來他們發現了。。

4. 經曆的挫折

select c2.id,c2.name,c2.user,c2.categoryname, Max(c2.version) version from component c2 where  c2.user="tan"  group by c2.name;

這樣在資料庫中查詢時是沒有問題的,關鍵是在項目中一般是物件導向的,如果在項目中改為如下:

select c.componentId.name,Max(c.componnetId.version.versionString) from component cwhere c.owner=:userId group by c.componentId.name

發現能正常顯示,但是當在前面加入其它欄位(比如:c.image)它就會報錯了,如果想讓它不報錯就得以它來分組,但是在實際情況中絕不可能這麼做,因為組件相同但是版本是不同的。

5. 最終的解決方案
上面的物件查詢中只用一個組件名並不能唯一確定一個對應版本的組件,那麼如何來唯一確定呢?
我想了很久也沒有想到解決辦法,後來在我的組長的協助下,終於解決了這個問題。

既然一個欄位不能唯一確定,為什麼不用2個欄位進行唯一確定呢?

CONCAT(s1,s2) 串連連個字串 字串函數 JPQHQL HQL CONCAT([對象屬性],[對象屬性])

使用CONCAT函數就能夠使得組件名和版本後捆綁在一起,就能夠唯一確定最新版本的組件。

最終解決,代碼如下:

 select component from Component component where component.owner=:userId and CONCAT(component.componentId.name,component.componentId.version.versionString)  in (select CONCAT(c.componentId.name,Max(c.componentId.version.versionString)) from Component c group by c.componentId.name )

6.反思

遇到問題,一定要敢於去想,敢於往不同的層面去想並不斷的嘗試去解決它,切記不能夠固執己見,停在原地打轉,柳暗花明往往就在于思想越界的一瞬間。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.