Hibernate中利用配置文件(hbm)自动生成数据库表

来源:互联网 发布:js array sort 源码 编辑:程序博客网 时间:2024/04/29 03:38
        接上一篇文章,上篇文章介绍了如何利用XDoclet从类自动生成hbm配置文件,这篇写一下如何自动通过hbm文件自动建立数据库表 。以类为基础,生成配置文件和数据库表,更加符合OO。
       上一篇文章自动生成了Position.hbm.xml和Users.hbm.xml两个配置文件,将其加入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) {
        
/**
         * 根据映射文件创建数据库结构
         
*/

        
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(
truetrue);

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

            tx.commit();

        }
 catch (HibernateException e) {
            e.printStackTrace();
            
try {
                tx.rollback();
            }
 catch (HibernateException e1) {
                e1.printStackTrace();
            }

        }
 finally {

        }

    }


}


运行,出现如下输出:
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.

现在看看数据库,已经成功地创建了test_position、test_uses和test_user_position 三张表。

利用这两篇文章中的方法,可以先进行Java类的设计,再自动生成配置文件和数据库表,这样做更见符合OO的设计思想,但是如果遇到表与表之间关系复杂,可能就不是很适合了。嘿嘿