在工作中,我们常常会碰到具有递归性质记录的数据,最常见的是某个机构部门节点的数据,某个节点一定会有个父节点属性,同时它也许会有若干子节点。所有的节点数据都会存在数据库中一张表中。这种现象在设计模式上叫Composite模式。下面我就给出一个用hibernate操作这种表的例子,关于hibernate配置和建立表结构的部分请参考我的前一篇文章《利用weblogic的数据源作为hibernate的数据源的例子》
1.持久化类Node.java
- package com.jagie.business.organization;
- /**
- * <p>Title: </p>
- * <p>Description: 部门节点</p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: www.jagie.com</p>
- * @author Jagie
- * @version 1.0
- */
- public class Node {
- private String ID;//pk
- private String name;//名称
- private String description;//描述
- private Node parent;//上级部门
- private java.util.Set children;//下级部门
- 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.映射文件Node.hbm.xml
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> <hibernate-mapping> <class name="com.jagie.business.organization.Node" table="SYS_Node"> <id name="ID"> <generator class="uuid.hex" /> </id> <property name="name" /> <property name="description" /> <set cascade="save-update" inverse="true" lazy="true" name="children"> <key column="parent" /> <one-to-many class="com.jagie.business.organization.Node" /> </set> <many-to-one cascade="none" class="com.jagie.business.organization.Node" column="parent" name="parent" /> </class> </hibernate-mapping>
3.用SchemaExport创建数据库(略)
4.测试的代码片断
- //获取net.sf.hibernate.Session和net.sf.hibernate.Transaction;
- Session s = JDOUtils.getInstance().getSessionFactory().openSession();
- Transaction t = s.beginTransaction();
- //建立父节点
- Node org = new Node();
- org.setName("北京总公司");
- org.setDescription("这是北京总公司");
- //建立子节点
- Node org2 = new Node();
- org2.setName("海淀分公司");
- org2.setDescription("这是海淀分公司");
- //建立子节点对父节点的引用
- org2.setParent(org);
-
- //持久化
- s.save(org);
- s.save(org2);
- t.commit();
- s.close();
代码运行后,我们观察数据库,发现已经生成表SYS_Node,其结构为 id varchar2(255) name varchar2(255) y description varchar2(255) y parent varchar2(255) y
其中y的意思为nullable(可空),同时把我们的节点数据正确的插入了。 你可以自己再用session.find()方法来找出某父节点下面的所有子节点了。 最后,希望这篇短文对你有用。
|