How to show tree-view replies to message? Java & Hibernate
I have message, and need to show ten (for example) first 'root' replies with all the replies to itselfs, and it should look like a tree. (Standard messages and tree replies view, you know). So, the question is - how to get it from DB - i'm using hibernate, and afaik it will get a lot of time - to retrieve the WHOLE collection itself, with all subtrees, recursively. (And, maybe, its good only for small-sized collections, otherwise recursion will cause a stack overflow (Ha-ha. Here we are :) ) Is there a more efficient decision?
So now I have smth like code below, but I need ano开发者_StackOverflowther one way (BaseEntry is class for both the message and any reply) :
@Entity public class BaseEntry extends VersionedEntity {
private @Nullable BaseEntry parent;
@ManyToOne
@ForeignKey(name="base_entry_parent__base_entry_fk")
@Nullable public BaseEntry getParent()
{
return parent;
}
@OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
private List<BaseEntry> children;
...
Could you advice something, please?
There is a more efficient solution, but it will mean completely changing how you store things in the database. Read http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ to learn how to use nested set trees. That approach makes writes expensive, but reads much, much cheaper. If you add in a flag for root nodes that you have indexed, then it is easy to fetch your list of root nodes, then fetch the subtrees.
There is a significant modification that I would suggest to their approach. They used sets of integers with no gaps at all. This means that every write has to renumber everything in the tree. This makes writes a lot more expensive. But suppose that you start root nodes out with gaps of 2**20 instead, and have each child by default take up half the space available to it. Then you don't have to do any renumbering at all until you have a set of replies that is 21 deep or wide. And when you do renumber, you can renumber just the subtree below that root node, because you still have plenty of gaps to use.
精彩评论