Posted on 2007-12-11 17:51
G_G 閱讀(1672)
評論(1) 編輯 收藏 所屬分類:
hibernate
對hbn深入過程中,發(fā)現(xiàn)開發(fā)和設計持久層 到項目后期,越來越困難。在次仔細查分析。特總結一種開發(fā)方法。留下與大家分享,歡迎拍磚。
開發(fā)過程描述:1.使用 MyEclipes -> uml? 創(chuàng)建類圖
2.用 Generate java Code 根據(jù)類圖生成 java文件
3.使用 Xdoclet 添加 Hbn 標簽
4.配置myEclipes -> XDoclet 自動生成 mapping.hbn.xml
5.使用myEclipes 把項目轉化成 hibernate? 項目
6.使用 org.hibernate.tool.hbm2ddl.SchemaExport 建表
開發(fā)過程好處:1)完全是面向?qū)ο?,不需要寫xml配置文件(XDoclet);
2)項目后期修改容易面對uml
3)用myEclipes 這些都不用去找,直接拿來用(uml,XDoclet,hibernate ..)
下面就來個 小例把
1.MyEclipes 使用 uml 參考->
MyEclipse 5.5 UML 入門視頻 (
作者:BeanSoft)

2.由uml生成類文件

3.先使用 eclipes的 快鍵方法寫 get/set 方法, 類文件文件添加 hbn XDoclet的注解
package?bean;
/**?
?*?@hibernate.class?table="t1oo"
?*/
public?class?T1oo?{
??public?int?id;
??public?String?name;
??public?int?avg;
??
??/**?
???*?@hibernate.property?
???*?column="avg"
???*?length="4"
???*?not-null="true"
???*/
public?int?getAvg()?{
????return?avg;
}
public?void?setAvg(int?avg)?{
????this.avg?=?avg;
}
/**
?*?@hibernate.id?
?*?column="id"
?*?generator-class="hilo"
?*/
public?int?getId()?{
????return?id;
}
public?void?setId(int?id)?{
????this.id?=?id;
}
/**
?*?@hibernate.property?
?*?column="name"
?*?not-null="true"?
?*?@return
?*/
public?String?getName()?{
????return?name;
}
public?void?setName(String?name)?{
????this.name?=?name;
}
??
}
4.用myEclipes 生成 XDoclet
在項目點右鍵-> properties -> MyEclipse-XDoclet ->
在Configuration 空白初點右鍵 選 add standard -> ... hbn 后面不太好描述 可以查下很簡單的 。配置好了運行后就可以看見 多了 個 T1oo.hbm.xml 文件;
5.myEclipes + hbn 就不多說了
6. hbn2java:
????public?void?testCreateTable()throws?Exception{
?????????HibernateSessionFactory.currentSession();
?????????HibernateSessionFactory.closeSession();
?????????
?????????Field[]?ff?=?HibernateSessionFactory.class.getDeclaredFields();
?????????Field?fie?=?null?;
?????????for(int?i=0;i<ff.length;i++){
?????????????if(?ff[i].getType().equals(?Configuration.class?)?){
?????????????????fie?=?ff[i];
?????????????}
?????????}
?????????fie.setAccessible(true);
?????????Configuration?cfg?=?(Configuration)fie.get(HibernateSessionFactory.class);
?????????cfg.addInputStream(?this.getClass().getResourceAsStream("/bean/T1oo.hbm.xml")?);
???????? //建表
??????????SchemaExport?dbExport?=?new?SchemaExport(cfg);
??????????dbExport.setOutputFile("c:\\db\\test.txt");
??????????dbExport.create(true,?true);?
????}
sql:
drop table if exists t1oo
drop table if exists hibernate_unique_key
create table t1oo (
??? id integer not null,
??? avg integer not null,
??? name varchar(255) not null,
??? primary key (id)
)
create table hibernate_unique_key (
???? next_hi integer
)
insert into hibernate_unique_key values ( 0 )
效果:
mysql> show tables;
+----------------------+
| Tables_in_hbn??????? |
+----------------------+
| hibernate_unique_key |
| t1oo???????????????? |
+----------------------+
2 rows in set (0.00 sec)