注:使用前需把數據庫建好,運行完成後,原有數據會被清空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