• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
Bartenders:
  • Piet Souris
  • Jj Roberts
  • fred rosenberger

Simple Hibernate Tree Example

 
Ranch Hand
Posts: 42
3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Tree Example

This is the simplest way to illustrate a tree structure in Hibernate that I could cook up.

This example has only one persistent class: TreeNode. Notice that the annotations on TreeNode._children and TreeNode._parent show the semantics of the tree.

Then notice that this is an ordinary container/contained relationship. There really is nothing special about building a persistent tree.

This example relies on the semantics of eager loading. See my eager loading example and my lazy loading example.

This example also relies on the semantics of cascade saving. See my cascade save example.

Note: The original version of this post had a time-bomb in it. It would work as originally presented, but it could cause bizarre behavior if the pattern were used in a larger project. The original had an improper use of a java.util.List on line 11 of TreeNode.java (now it uses a java.util.Set). The issue is fully explained in my simple Hibernate list example.

Notice: This is provided with no warranty whatsoever. Use at your own risk.

This is the node class:

This is an example of how to use the persistent tree:
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, Chris.
I lern you post as one of ways saving and reading like-tree data structe in/from database.

I found litle bug in class TreeNode.
You change type variable _children from java.util.Set<TreeNode>, but forgot change method getChildren in line 58-61.

I suggest next change in line 60:
return java.util.Collections.unmodifiableList( _children.stream().collect(Collectors.toList()) );

Thank you
 
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic