首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Hibernate多对1自身关联

2012-10-08 
Hibernate多对一自身关联说明:一个部门有若干个子部门,子部门还可以有子部门,本文通过这个演示myeclipse如

Hibernate多对一自身关联
说明:一个部门有若干个子部门,子部门还可以有子部门,本文通过这个演示myeclipse如何实现这种树形关系的持久化。

开发工具:myeclipse 7.0 GA
数 据 库:mysql-5.0.41
操作系统:windows xp professional 中文版

步骤:
1、建立mysql5数据库testdb,脚本下面已经给出。
2、配置myeclipse的数据库服务器,并建立名称为mysql的数据库链接。
3、建议myeclipse的web工程,名称为hibernateRel,并加入hibernate支持。
4、在myeclipse的数据库视图中链接数据库并通过表生成实体POJO和配置文件,中间不生成DAO。
5、检查配置文件的正确性,然后测试类进行测试。


一、建立数据库的脚本:

drop table if exists part;

-- alter table part drop foreign key fk_part;

create table part(
id bigint not null primary key,
name varchar(20),
father_id bigint
);

alter table part add index fk_part (father_id),
add constraint fk_part foreign key (father_id) references part(id);

表关系的逻辑图:




三、写测试类进行测试:
Test.java

D:\mysql-5.0.41-win32\bin>mysql -uroot -123456Welcome to the MySQL monitor.  Commands end with ; or \g.Your MySQL connection id is 13Server version: 5.0.41-community MySQL Community Edition (GPL) Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> use testdb;Database changed mysql> describe part;+-----------+-------------+------+-----+---------+-------+| Field     | Type        | Null | Key | Default | Extra |+-----------+-------------+------+-----+---------+-------+| id        | bigint(20)  | NO   | PRI |         |       || name      | varchar(20) | YES  |     | NULL    |       || father_id | bigint(20)  | YES  | MUL | NULL    |       |+-----------+-------------+------+-----+---------+-------+3 rows in set (0.00 sec) mysql> select * from part;+----+------+-----------+| id | name | father_id |+----+------+-----------+|  1 | p1   |      NULL ||  2 | p12  |         1 ||  3 | p11  |         1 |+----+------+-----------+3 rows in set (0.00 sec) mysql>


测试结果表明,保存父机关的时候,可以级联保存父机关下的子机关。

总结:这个表建立好后,由myeclipse生成的POJO不需要做任何改动,生成的mapping也需要添加一个cascade="save-update"。然后就直接写测试类进行测试。

本文出自 “熔 岩” 博客,转载请与作者联系! 1 楼 wpfwupengfeiwpf 2010-09-11   你好,我想请问如何将父类father_id为null的记录在保存时保存为0

热点排行