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实体类: