I'm writing a data tree structure that is combined from a Tree and a TreeNode. Tree will contain the root and the top level actions on the data. I'm using a UI library to present the tree in a windows form where I can bind the tree to the TreeView.
I will need to save this tree and nodes in the DB. What will be the best way to save the tree and to get the following features:
I had 2 ideas. The first is to serialize the data into a one liner in a table. The second is to save in tables but then, when moving to data entities I will loose the row states on the table on changed nodes.
Any ideas?
Connect any output containing data to the input of the Param Viewer. To show the tree, right-click the Param Viewer and select “draw tree.” In this example, the Param Viewer is connected to the Points (P) output of a Divide Curve component that divided 10 curves into 10 segements each.
In the SQL tree structure, every node has its own, unique id. It has a reference to the parent node. For every node in a submenu we need its sequence number for ordering purposes. The name column is just a label which will be shown on the website.
Adjacency List is a design method for implementing hierarchical data. It's achieved by storing the ID of the related record on the desired record. You add one column to your table, and set it as a foreign key to the same table's primary key. This is the method that I recommend using for most cases.
The standard method of storing hierarchical data is simple parent-child relationship. Each record in the database includes a —parent id—, and a recursive query through the records build the children, siblings, and levels of the tree.
I've bookmarked this slidshare about SQL-Antipatterns, which discusses several alternatives: http://www.slideshare.net/billkarwin/sql-antipatterns-strike-back?src=embed
The recommendation from there is to use a Closure Table (it's explained in the slides).
Here is the summary (slide 77):
| Query Child | Query Subtree | Modify Tree | Ref. Integrity Adjacency List | Easy | Hard | Easy | Yes Path Enumeration | Easy | Easy | Hard | No Nested Sets | Hard | Easy | Hard | No Closure Table | Easy | Easy | Easy | Yes
The easiest implementation is adjacency list structure:
id parent_id data
However, some databases, particularly MySQL
, have some issues in handling this model, because it requires an ability to run recursive queries which MySQL
lacks.
Another model is nested sets:
id lft rgt data
where lft
and rgt
are arbitrary values that define the hierarchy (any child's lft
, rgt
should be within any parent's lft
, rgt
)
This does not require recursive queries, but it slower and harder to maintain.
However, in MySQL
this can be improved using SPATIAL
abitilies.
See these articles in my blog:
for more detailed explanations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With