开发者

How do I sort a linked list in hql?

Same question as this, only I'd like to do it in Hibernate (using grails if that matters).

So the domain class looks like this

class LinkedElement {
  LinkedElement precedingElement
  String someData
}

and I'd like to query all elements in their linked order (where the first LinkedElement has null as the precedingElement). Is this possible in 开发者_Go百科an efficient way?


You can only easily find out who is at the front of the line (i.e. preceding element is null). Unfortunately, that means you're in N+1 query territory to get the whole list.

Query 1 - who's in front 
Query 2 - who's behind 1
Query 3 - who's behind 2
....
Query n - who's behind n-1
Query n+1 - who's behind n -> no one is behind n, I must be at the end

Referring to the question you mentioned, don't mistake efficient for syntactically concise. Just because some DBMS will give you convenient syntax they are still solving the same problem by either a.) performing the same inefficient algorithm but with simplified syntax or b.) indexing things ahead of time so the DBMS has access to your data efficiently even though you didn't model it that way. So, if you absolutely have to solve this problem with the specified data structure using hibernate, then you should look at using a Native SQL Query, tuning at the database level, taking advantage of the features your DBMS may offer you in this area.

If you think about the data structure you're using, it's great for representing a Stack. You can push, pop, and top with just a couple operations each. In general, that's what unidirectional linked lists are good for. For something like a queue, you'd want to think about using a bidirectional linked list since you can dequeue, front, and enqueue with just a couple operations each. For dynamically adding elements into a list, LinkedLists are great. For getting a whole list of things in order then LinkedLists are pretty inefficient by themselves - you're looking at n+1 or n operations depending on single or bidirectional. Instead, an ArrayList is the way to go. Want to know what the third element is? Cool, use its index. Compared to linked list where you need to use first.getNext.getNext this is way more efficient! But if you need to add stuff to the list or use it for a queuing or stack type application then it's definitely got its drawbacks - resizing arrays is expensive compared to adding a new link in a linked list.

I wish I had a better answer for you, but hopefully this is at least somewhat useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜