首先,在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">
<!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration>
<session-factory> <property name="connection.username">root</property> <property name="connection.url"> jdbc:mysql://localhost:3306/hxview?useUnicode=true&characterEncoding=gbk </property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="myeclipse.connection.profile">mysql</property> <property name="connection.password">download</property> <property name="connection.driver_class"> org.gjt.mm.mysql.Driver </property> <property name="show_sql">true</property> <mapping resource="org/hx/model/projectList/ProjectList.hbm.xml" /> <mapping resource="org/hx/model/about/About.hbm.xml" /> <mapping resource="org/hx/model/gongshi/Gongshi.hbm.xml" /> <mapping resource="org/hx/model/projectinfo/ProjectInfo.hbm.xml" /> <mapping resource="org/hx/model/message/Message.hbm.xml" /> <mapping resource="org/hx/model/newsList/Newslist.hbm.xml" /> <mapping resource="org/hx/model/userList/Userlist.hbm.xml" />
</session-factory> </hibernate-configuration>
?
其中,数据库名为:hxview ,org/hx/model/projectList/ProjectList.hbm.xml为包路径下的实体配置文件。
接下来,就是编写生成表的代码了,很简单,代码如下:
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 {
} }
} 在运行前,请先确定数据库服务已经开启,并且数据库中存在名称为hxview的库,运行后,会将库里面的表删除,然后重新建表,所以,必须注意重要的数据是否已经保存!
运行结果如下:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environmen
免责声明: 本文仅代表作者个人观点,与爱易网无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
|