用hibernate生成数据库表结构

hibernate生成数据库表结构大概分为两步,当然也必须先搭好hibernate环境 把hibernate的包与数据库连接包都加到项目中。

第一步:配置文件,hibernate的配置文件,实体的配置文件就不详解了,这讲hibernate的配置文件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.url">
 	 jdbc:sqlserver://localhost:1433;DatabaseName=zsflow <!--数据库名  -->
 </property>
 <property name="dialect">
 	 org.hibernate.dialect.SQLServerDialect <!--连接数据库方言  -->
 </property>
 <property name="connection.driver_class">
  	 com.microsoft.sqlserver.jdbc.SQLServerDriver <!-- 连接类 -->
 </property> 
 <property name="connection.username">sa</property> <!-- 用户名  -->
 <property name="connection.password">sql,123</property>  <!-- 密码  -->
 <property name="show_sql">true</property>
 <mapping resource="com/gouge/main/bean/BwfConditionCofig.hbm.xml" />  <!-- 加载的hbm文件 -->
 <mapping resource="com/gouge/main/bean/BwfExecType.hbm.xml" />
 <mapping resource="com/gouge/main/bean/BwfReportConfig.hbm.xml" />
</session-factory>
</hibernate-configuration> 

前面的5个property是配置的连接数据库的信息,后面的property是配置的实体类的配置文件如

 <mapping resource="com/gouge/main/bean/BwfConditionCofig.hbm.xml" />

在这配置了的hbm文件都会生成数据库结构。

第二步:写个java类,生成表结构。

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 {
			//加载hibernate 配置文件
			config = new Configuration().configure(new File("resource/hibernate.cfg.xml"));
			//创建sessionFactory
			SessionFactory sessionFactory = config.buildSessionFactory();
			//打开sessionFactory
			session = sessionFactory.openSession();
			//开启事物
			tx = session.beginTransaction();
			SchemaExport schemaExport = new SchemaExport(config);
			//创建数据库表结构
			schemaExport.create(true, true);
			//提交事物
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			try {
				tx.rollback();//回滚事物
			} catch (HibernateException e1) {
				e1.printStackTrace();
			}
		} finally {
			System.out.println("创建表格成功");
		}
	}

}

执行上面的java类,就会创建好在hibernate.cfg.xml中配置好了的hbm文件的表结构。

备注:hbm文件的建立与实体的创建在这就不详解了 截图如下:

hbm文件:


java实体类:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值