接上一篇文章,上篇文章介紹了如何利用XDoclet從類自動(dòng)生成hbm配置文件,這篇寫一下如何自動(dòng)通過hbm文件自動(dòng)建立數(shù)據(jù)庫表 。以類為基礎(chǔ),生成配置文件和數(shù)據(jù)庫表,更加符合OO。
上一篇文章自動(dòng)生成了Position.hbm.xml和Users.hbm.xml兩個(gè)配置文件,將其加入hibernate.cfg.xml中,然后建立HibernateSchemaExport類,代碼如下:
package test;

import java.io.File;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;


public class HibernateSchemaExport ...{

static Session session;

static Configuration config = null;
static Transaction tx = null;


public static void main(String[] args) ...{

/** *//**
* 根據(jù)映射文件創(chuàng)建數(shù)據(jù)庫結(jié)構(gòu)
*/

try ...{
config = new Configuration().configure(new File(
"src/hibernate.cfg.xml"));

System.out.println("Creating tables...");

SessionFactory sessionFactory = config.buildSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();

SchemaExport schemaExport = new SchemaExport(config);
schemaExport.create(true, true);

System.out.println("Table created.");

tx.commit();


} catch (HibernateException e) ...{
e.printStackTrace();

try ...{
tx.rollback();

} catch (HibernateException e1) ...{
e1.printStackTrace();
}

} finally ...{

}
}

}

運(yùn)行,出現(xiàn)如下輸出:
Creating tables...
alter table test_user_position drop foreign key FKF1F5A2301D5E879B
alter table test_user_position drop foreign key FKF1F5A2307D008B16
drop table if exists test_position
drop table if exists test_user_position
drop table if exists test_uses
create table test_position (
id integer not null auto_increment,
name integer,
primary key (id)
)
create table test_user_position (
position_id integer not null,
user_id integer not null,
primary key (user_id, position_id)
)
create table test_uses (
id integer not null auto_increment,
name varchar(25),
primary key (id)
)
alter table test_user_position
add index FKF1F5A2301D5E879B (user_id),
add constraint FKF1F5A2301D5E879B
foreign key (user_id)
references test_uses (id)
alter table test_user_position
add index FKF1F5A2307D008B16 (position_id),
add constraint FKF1F5A2307D008B16
foreign key (position_id)
references test_position (id)
Table created.
現(xiàn)在看看數(shù)據(jù)庫,已經(jīng)成功地創(chuàng)建了
test_position、test_uses和test_user_position 三張表。
利用這兩篇文章中的方法,可以先進(jìn)行Java類的設(shè)計(jì),再自動(dòng)生成配置文件和數(shù)據(jù)庫表,這樣做更見符合OO的設(shè)計(jì)思想,但是如果遇到表與表之間關(guān)系復(fù)雜,可能就不是很適合了。嘿嘿