Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store tree structures in Java?

Hierarchical data structures are often stored in relational databases. This kind of storage is flexible but flat, so the tree structure has to be build with each query. I want to store forum posts as a tree structure, but it should be possible to query efficiently, say for example selecting posts by date or author.

I'd like to have an open source database that is accessible from Java.

What is the best way to do so? CouchDB? neo4j? ...?

like image 497
deamon Avatar asked Mar 09 '10 12:03

deamon


People also ask

How are trees stored in Java?

A Tree is a non-linear data structure where data objects are organized in terms of hierarchical relationship. The structure is non-linear in the sense that, unlike simple array and linked list implementation, data in a tree is not organized linearly. Each data element is stored in a structure called a node.

How do you store a tree structure in a database?

The simplest way to serialize a tree is to give each node a parent_id column that contains the ID of the parent node. Any modification of the tree (like adding a node or changing a node's parent) only affect a single row in the table, so changes are fast. The number of queries grows with the depth of your tree.

How do you represent a tree in Java?

To build a tree in Java, for example, we start with the root node. Node<String> root = new Node<>("root"); Once we have our root, we can add our first child node using addChild , which adds a child node and assigns it to a parent node.

Does Java have a built in binary tree?

Example: Java Program to Implement Binary Tree Unlike other data structures, Java doesn't provide a built-in class for trees. Here, we have created our own class of BinaryTree . To learn about the binary tree, visit Binary Tree Data Structure.


1 Answers

When I first encountered this problem, I've found the great article (link).

In tho words: in RDBMS world there are 2 main tree model storage approaches:

  • The Adjacency List Model
  • The Nested Set Model
like image 191
Yuri.Bulkin Avatar answered Sep 18 '22 09:09

Yuri.Bulkin