During work, we often encounter data with recursive records. The most common is the data of a department node of an organization. A node must have a parent node attribute, at the same time, it may have several subnodes. All node data is stored in a table in the database. This phenomenon is called the Composite mode in the design mode. Next I will give an example of using hibernate to operate such a table. For the hibernate configuration and table structure creation section, please refer to my previous article 《Example of using the weblogic data source as the hibernate Data Source"
1. Persistence class Node. java
- PackageCom. jarie. business. organization;
- /**
- *
Title:
- *
Description: department node
- *
Copyright: Copyright (c) 2003
- *
Company: www.jagie.com
- * @ Author Jagie
- * @ Version 1.0
- */
- Public ClassNode {
- Private StringID;// Pk
- Private StringName;// Name
- Private StringDescription;// Description
- PrivateNode parent;// Superior department
- PrivateJava. util.SetChildren;// Subordinate departments
- Public Static VoidMain (String[] Args ){
- }
- Public StringGetID (){
- ReturnID;
- }
- Public VoidSetID (StringID ){
- This. ID = ID;
- }
- Public StringGetName (){
- ReturnName;
- }
- Public VoidSetName (StringName ){
- This. Name = name;
- }
- PublicNode getParent (){
- ReturnParent;
- }
- Public VoidSetParent (Node parent ){
- This. Parent = parent;
- }
- Public StringGetDescription (){
- ReturnDescription;
- }
- Public VoidSetDescription (StringDescription ){
- This. Description = description;
- }
- Public StringToString (){
- ReturnName;
- }
- PublicJava. util.SetGetChildren (){
- ReturnChildren;
- }
- Public VoidSetChildren (java. util.SetChildren ){
- This. Children = children;
- }
- }
2. Map File Node. hbm. xml
column="parent" name="parent" />
3. Use SchemaExport to create a database (omitted)
4. Test code snippet
- // Obtain net. sf. hibernate. Session and net. sf. hibernate. Transaction;
- Session s = JDOUtils. getInstance (). getSessionFactory (). openSession ();
- Transaction t = s. beginTransaction ();
- // Create a parent node
- Node org =NewNode ();
- Org. setName ("Beijing Head Office ");
- Org. setDescription ("this is Beijing Head Office ");
- // Create a subnode
- Node org2 =NewNode ();
- Org2.setName ("Haidian branch ");
- Org2.setDescription ("this is the Haidian branch ");
- // Create a subnode reference to the parent node
- Org2.setParent (org );
- &