Posted on 2007-12-11 17:51 
G_G 阅读(1692) 
评论(1)  编辑  收藏  所属分类: 
hibernate 
			 
			
		 
		对hbn深入过程中,发现开发和设计持久层 到项目后期,越来越困难。在次仔细查分析。特总结一种开发方法。留下与大家分享,欢迎拍砖。
开发过程描述:1.使用 MyEclipes -> uml  创建类图 
2.用 Generate java Code 根据类图生成 java文件
3.使用 Xdoclet 添加 Hbn 标签
4.配置myEclipes -> XDoclet 自动生成 mapping.hbn.xml
5.使用myEclipes 把项目转化成 hibernate  项目
6.使用 org.hibernate.tool.hbm2ddl.SchemaExport 建表
开发过程好处:1)完全是面向对象,不需要写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)