At work, we often encounter data with recursive nature records, the most common is the data of a mechanism department node, and a node will have a parent node attribute, and it may have several sub-nodes. All node data exists in a table in the database. This phenomenon is called Composite mode in the design mode. Below I will give an example of operating this table with hibernate, please refer to my previous article for the Hibernate configuration and establishment of a table structure.
Examples of using WebLogic data source as Hibernate data sources
"1. Persistence class node.javaPackage com.jagie.business.organization;
/ ** *
Title: p> *
Description: Department Node P> *
Copyright: Copyright (C) 2003 P> *
Company: www.jagie. COM p> * @Author jagie * @version 1.0 * /
Public class node {priz; // pk private string name; // Name Private string description; // Description
Private node parent; // superior department private java.util.set children; // lower sector
Public static void main (String [] args) {} public string getId () {return id;} public void setid (String ID) {this.id = ID;} public string getname () {return name;} public void setname (String name) {this.name = name;} public Node getParent () {return parent;} public void setParent (Node parent) {this.parent = parent;} public String getDescription () {return description;} public void setDescription (String description) {this.description = description;} public String toString () {return name;} public java.util.Set getChildren () {return children;} public void setChildren (java.util.Set children) {this. Children = children;}} 2. Mapping file node.hbm.xml [pre] xml version = '1.0' encoding = 'uTF-8'?>
[/ pre] 3. Create a database (omitted) 4. Test code snippet // get net.sf.hibernate.Session and Net.sf.hibernate.Transaction; session s = jdoutils.getInstance (). getsessionFactory () .openSession (); Transaction t = s.begintransaction (); // Establish a parent point
Node org = new node (); org.setname ("Beijing Corporation"); Org.SetDescription ("This is Beijing Corporation"); // Set up a child node
Node org2 = new node (); ORG2.SETNAME ("Haidian Branch"); ORG2.SETDESCRIPTION ("This is Haidian Branch"); // Establish a sub-node to parent node reference
ORG2.SETPARENT (ORG); // Persistence
S.Save (ORG); S.SAVE (ORG2); T.CMmit (); S.Close (); After the code is running, we observe the database and find that the table sys_node has been generated, and its structure is ID varchar2 (255) name varchar2 (255) y description varchar2 (255) y Parent varchar2 (255) Y where Y is NULLABLE (blank), and putting our node data correctly. You can use the session.find () method to find all the child nodes below a parent node. Finally, I hope this essay is useful to you.