注:使用前需把数据库建好,运行完成后,原有数据会被清空java
hibernate.cfg.xmlsql
<?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="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property> <property name="hibernate.connection.url">jdbc:sqlserver://192.168.56.101:1433;databasename=TestDB</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.connection.password">admin</property> <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property> <property name="connection.autoReconnect">true</property> <property name="connection.autoReconnectForPools">true</property> <property name="connection.is-connection-validation-required">true</property> <property name="hibernate.c3p0.min_size">2</property> <property name="hibernate.c3p0.timeout">5000</property> <property name="hibernate.c3p0.max_statements">100</property> <property name="hibernate.c3p0.idle_test_period">3000</property> <property name="hibernate.c3p0.acquire_increment">2</property> <property name="hibernate.c3p0.validate">false</property> <mapping resource="com/lvy/server/model/Test.hbm.xml" /> </session-factory> </hibernate-configuration>
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; /** * 经过hibernate配置文件生成数据库表 * * @author Albert Smith * */ public class InitDB { static Session session; public static void main(String[] args) { Configuration config = null; Transaction tx = null; try { config = new Configuration().configure(new File("config/hibernate.cfg.xml")); //读取hibernate配置文件 System.out.println("开始创表"); SchemaExport schemaExport = new SchemaExport(config); schemaExport.create(true, true); System.out.println("建立结束"); SessionFactory sessionFactory = config.buildSessionFactory(); session = sessionFactory.openSession(); tx = session.beginTransaction(); tx.commit(); } catch (HibernateException e) { e.printStackTrace(); try { tx.rollback(); } catch (HibernateException e1) { e1.printStackTrace(); } } finally { } } }
每次修改hibernate配置文件后,运行一下,就能够自动更新表结构。session