hibernate生成数据库表
注:使用前需把数据库建好,运行完成后,原有数据会被清空
hibernate.cfg.xml
com.microsoft.sqlserver.jdbc.SQLServerDriver jdbc:sqlserver://192.168.56.101:1433;databasename=TestDB sa admin org.hibernate.dialect.SQLServerDialect true org.hibernate.cache.HashtableCacheProvider true true true 2 5000 100 3000 2 false
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配置文件后,运行一下,就可以自动更新表结构。