hibernate 根据配置文件自动生成数据库表

1、在项目src目录下,新建文件 hibernate.cfg.xml,内容如下:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

	<session-factory>
		<property name="connection.username">root</property>
		<property name="connection.url">
			jdbc:mysql://localhost:3306/bgm?useUnicode=true&characterEncoding=utf8&autoReconnect=true
		</property>
		<property name="dialect">
			org.hibernate.dialect.MySQLDialect
		</property>
		<property name="myeclipse.connection.profile">mysql</property>
		<property name="connection.password">370211</property>
		<property name="connection.driver_class">
			org.gjt.mm.mysql.Driver
		</property>
		<property name="show_sql">true</property>
		<mapping resource="com/evisit/BO/ErSource.hbm.xml" />
		<mapping resource="com/evisit/BO/ErCity.hbm.xml" />
		<mapping resource="com/evisit/BO/ErUser.hbm.xml" />
		<mapping resource="com/evisit/BO/ErMother.hbm.xml" />
		<mapping resource="com/evisit/BO/ErArea.hbm.xml" />
		<mapping resource="com/evisit/BO/ErHospital.hbm.xml" />
		<mapping resource="com/evisit/BO/ErSheet.hbm.xml" />
		<mapping resource="com/evisit/BO/ErTsresult.hbm.xml" />
		<mapping resource="com/evisit/BO/ErQues.hbm.xml" />
		<mapping resource="com/evisit/BO/ErTstask.hbm.xml" />
		<mapping resource="com/evisit/BO/ErSheetQues.hbm.xml" />
		<mapping resource="com/evisit/BO/ErQuesOption.hbm.xml" />
		<mapping resource="com/evisit/BO/ErCause.hbm.xml" />
		<mapping resource="com/evisit/BO/ErMilk.hbm.xml" />
		<mapping resource="com/evisit/BO/ErSample.hbm.xml" />
	</session-factory>
</hibernate-configuration>

需要生成的数据库表就是 mapping 对应的xml文件,如下图:

 

2、Java实现类:

package utils;

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(true, true);

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

			tx.commit();

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

		}
	}

}


在运行前,请先确定数据库服务已经开启,并且数据库中存在名称为bgn的库,运行后,会将库里面的表删除,然后重新建表,所以,必须注意重要的数据是否已经保存!

另外,需要的jar包有下面几个(此处几个就够了,具体情况具体分析,不同项目可能还会用到其他jar包),如图:

 

运行main方法,数据库中就生成对应数据表了。

 

下面贴一下运行后的控制台输出:

2013-10-17 18:03:06 org.hibernate.cfg.Environment <clinit>
信息: Hibernate 3.1.3
2013-10-17 18:03:06 org.hibernate.cfg.Environment <clinit>
信息: hibernate.properties not found
2013-10-17 18:03:06 org.hibernate.cfg.Environment <clinit>
信息: using CGLIB reflection optimizer
2013-10-17 18:03:06 org.hibernate.cfg.Environment <clinit>
信息: using JDK 1.4 java.sql.Timestamp handling
2013-10-17 18:03:06 org.hibernate.cfg.Configuration configure
信息: configuring from file: hibernate.cfg.xml
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErSource.hbm.xml
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErSource -> er_source
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErCity.hbm.xml
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErCity -> er_city
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErUser.hbm.xml
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErUser -> er_user
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErMother.hbm.xml
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErMother -> er_mother
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErArea.hbm.xml
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErArea -> er_area
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErHospital.hbm.xml
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErHospital -> er_hospital
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErSheet.hbm.xml
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErSheet -> er_sheet
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErTsresult.hbm.xml
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErTsresult -> er_tsresult
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErQues.hbm.xml
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErQues -> er_ques
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErTstask.hbm.xml
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErTstask -> er_tstask
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErSheetQues.hbm.xml
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErSheetQues -> er_sheet_ques
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErQuesOption.hbm.xml
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErQuesOption -> er_ques_option
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErCause.hbm.xml
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErCause -> er_cause
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErMilk.hbm.xml
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErMilk -> er_milk
2013-10-17 18:03:07 org.hibernate.cfg.Configuration addResource
信息: Reading mappings from resource: com/evisit/BO/ErSample.hbm.xml
Creating tables...2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
信息: Mapping class: com.evisit.BO.ErSample -> er_sample
2013-10-17 18:03:07 org.hibernate.cfg.Configuration doConfigure
信息: Configured SessionFactory: null
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindCollectionSecondPass
信息: Mapping collection: com.evisit.BO.ErSheet.erSheetQueses -> er_sheet_ques
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindCollectionSecondPass
信息: Mapping collection: com.evisit.BO.ErQues.erQuesOptions -> er_ques_option
2013-10-17 18:03:07 org.hibernate.cfg.HbmBinder bindCollectionSecondPass
信息: Mapping collection: com.evisit.BO.ErQues.erSheetQueses -> er_sheet_ques

2013-10-17 18:03:08 org.hibernate.connection.DriverManagerConnectionProvider configure
信息: Using Hibernate built-in connection pool (not for production use!)
2013-10-17 18:03:08 org.hibernate.connection.DriverManagerConnectionProvider configure
信息: Hibernate connection pool size: 20
2013-10-17 18:03:08 org.hibernate.connection.DriverManagerConnectionProvider configure
信息: autocommit mode: false
2013-10-17 18:03:08 org.hibernate.connection.DriverManagerConnectionProvider configure
信息: using driver: org.gjt.mm.mysql.Driver at URL: jdbc:mysql://localhost:3306/bgm?useUnicode=true&characterEncoding=utf8&autoReconnect=true
2013-10-17 18:03:08 org.hibernate.connection.DriverManagerConnectionProvider configure
信息: connection properties: {user=root, password=****}
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: RDBMS: MySQL, version: 5.1.66-community
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.0.4 ( $Date: 2006-10-19 17:47:48 +0200 (Thu, 19 Oct 2006) $, $Revision: 5908 $ )
2013-10-17 18:03:08 org.hibernate.dialect.Dialect <init>
信息: Using dialect: org.hibernate.dialect.MySQLDialect
2013-10-17 18:03:08 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
信息: Using default transaction strategy (direct JDBC transactions)
2013-10-17 18:03:08 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
信息: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Automatic flush during beforeCompletion(): disabled
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Automatic session close at end of transaction: disabled
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: JDBC batch size: 15
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: JDBC batch updates for versioned data: disabled
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Scrollable result sets: enabled
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: JDBC3 getGeneratedKeys(): enabled
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Connection release mode: auto
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Maximum outer join fetch depth: 2
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Default batch fetch size: 1
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Generate SQL with comments: disabled
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Order SQL updates by primary key: disabled
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
信息: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
2013-10-17 18:03:08 org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
信息: Using ASTQueryTranslatorFactory
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Query language substitutions: {}
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Second-level cache: enabled
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Query cache: disabled
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory createCacheProvider
信息: Cache provider: org.hibernate.cache.EhCacheProvider
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Optimize cache for minimal puts: disabled
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Structured second-level cache entries: disabled
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Echoing all SQL to stdout
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Statistics: disabled
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Deleted entity synthetic identifier rollback: disabled
2013-10-17 18:03:08 org.hibernate.cfg.SettingsFactory buildSettings
信息: Default entity-mode: pojo
2013-10-17 18:03:08 org.hibernate.impl.SessionFactoryImpl <init>
信息: building session factory
2013-10-17 18:03:08 net.sf.ehcache.config.ConfigurationFactory parseConfiguration
警告: No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/E:/pansoft/Hibernate/WebRoot/WEB-INF/lib/ehcache-1.2.3.jar!/ehcache-failsafe.xml
2013-10-17 18:03:09 org.hibernate.impl.SessionFactoryObjectFactory addInstance
信息: Not binding factory to JNDI, no JNDI name configured
2013-10-17 18:03:09 org.hibernate.dialect.Dialect <init>
信息: Using dialect: org.hibernate.dialect.MySQLDialect
2013-10-17 18:03:09 org.hibernate.tool.hbm2ddl.SchemaExport execute
信息: Running hbm2ddl schema export
2013-10-17 18:03:09 org.hibernate.tool.hbm2ddl.SchemaExport execute
信息: exporting generated schema to database
2013-10-17 18:03:09 org.hibernate.connection.DriverManagerConnectionProvider configure
信息: Using Hibernate built-in connection pool (not for production use!)
2013-10-17 18:03:09 org.hibernate.connection.DriverManagerConnectionProvider configure
信息: Hibernate connection pool size: 20
2013-10-17 18:03:09 org.hibernate.connection.DriverManagerConnectionProvider configure
信息: autocommit mode: false
2013-10-17 18:03:09 org.hibernate.connection.DriverManagerConnectionProvider configure
信息: using driver: org.gjt.mm.mysql.Driver at URL: jdbc:mysql://localhost:3306/bgm?useUnicode=true&characterEncoding=utf8&autoReconnect=true
2013-10-17 18:03:09 org.hibernate.connection.DriverManagerConnectionProvider configure
信息: connection properties: {user=root, password=****}
alter table er_ques_option drop foreign key FK1AAAE2F0B56C4C52
alter table er_sheet_ques drop foreign key FK66848B84B56C4C52
alter table er_sheet_ques drop foreign key FK66848B844BCAC666
drop table if exists er_area
drop table if exists er_cause
drop table if exists er_city
drop table if exists er_hospital
drop table if exists er_milk
drop table if exists er_mother
drop table if exists er_ques
drop table if exists er_ques_option
drop table if exists er_sample
drop table if exists er_sheet
drop table if exists er_sheet_ques
drop table if exists er_source
drop table if exists er_tsresult
drop table if exists er_tstask
drop table if exists er_user
create table er_area (area_code varchar(10) not null, area_name varchar(60), city_code varchar(30) not null, primary key (area_code))
create table er_cause (cause_code varchar(10) not null, cause_name varchar(30), primary key (cause_code))
create table er_city (city_code varchar(30) not null, city_name varchar(30), primary key (city_code))
create table er_hospital (hospital_code varchar(10) not null, hospital_name varchar(60), city_code varchar(30), primary key (hospital_code))
create table er_milk (milk_code varchar(10) not null, milk_name varchar(50) not null, milk_type varchar(10) not null, primary key (milk_code, milk_name, milk_type))
create table er_mother (mother_id bigint not null, batch_id integer, mother_name varchar(50), mother_addr varchar(100), sample_standard varchar(100), total_money varchar(255), phone_one varchar(20), phone_two varchar(20), mobile_phone varchar(20), baby_birthday varchar(23), create_time varchar(23), city_code varchar(10), area_code varchar(10), area_name varchar(50), hospital_code varchar(10), hospital_name varchar(50), from_hospital varchar(20), shop_name varchar(100), source_code varchar(10), source_name varchar(40), conscribe_time varchar(23), deputy_name varchar(30), mother_desc varchar(100), repeat_num integer, current_sheet integer, current_max_days integer, bir_hospital_code varchar(10), stop_milk_month integer, bb_name varchar(20), bb_sex varchar(6), bb_index integer, create_user varchar(10), create_num integer, current_ts_agent varchar(10), current_ts_status integer, hcp_code varchar(20), sx_type varchar(20), sx_num integer, primary key (mother_id))
create table er_ques (quesid integer not null, quesname varchar(200), questype integer, citycode varchar(255), quesdesc varchar(255), primary key (quesid))
create table er_ques_option (quesoptid varchar(32) not null, quesid integer, optcode varchar(5), optdesc varchar(255), primary key (quesoptid))
create table er_sample (sample_code varchar(30) not null, sample_name varchar(30) not null, primary key (sample_code, sample_name))
create table er_sheet (sheetid integer not null, sheetname varchar(200), sheetdesc varchar(255), bb_min_age integer, bb_max_age integer, primary key (sheetid))
create table er_sheet_ques (sheetquesid varchar(32) not null, quesid integer, sheetid integer, seq integer, primary key (sheetquesid))
create table er_source (source_code varchar(10) not null, source_name varchar(40), primary key (source_code))
create table er_tsresult (task_result_id bigint not null, task_id bigint not null, ques_id integer, answer varchar(250), answer_add varchar(250), primary key (task_result_id))
create table er_tstask (task_id bigint not null, mother_id bigint not null, sheet_id bigint, creator_id varchar(20), creator_name varchar(20), creator_time varchar(20), executor_id varchar(20), executor_name varchar(20), executor_time varchar(20), status integer, ts_result integer, ts_desc varchar(250), primary key (task_id))
create table er_user (user_id varchar(32) not null, city_code varchar(20), user_byname varchar(20), user_name varchar(50), user_pwd varchar(40), user_type integer, create_time varchar(23), money2 integer, money3 integer, money4 integer, money_sheet integer, primary key (user_id))
alter table er_ques_option add index FK1AAAE2F0B56C4C52 (quesid), add constraint FK1AAAE2F0B56C4C52 foreign key (quesid) references er_ques (quesid)
alter table er_sheet_ques add index FK66848B84B56C4C52 (quesid), add constraint FK66848B84B56C4C52 foreign key (quesid) references er_ques (quesid)
alter table er_sheet_ques add index FK66848B844BCAC666 (sheetid), add constraint FK66848B844BCAC666 foreign key (sheetid) references er_sheet (sheetid)
2013-10-17 18:03:11 org.hibernate.tool.hbm2ddl.SchemaExport execute
信息: schema export complete
Table created.
2013-10-17 18:03:11 org.hibernate.connection.DriverManagerConnectionProvider close
信息: cleaning up connection pool: jdbc:mysql://localhost:3306/bgm?useUnicode=true&characterEncoding=utf8&autoReconnect=true



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值