Hibernate自动生成表

以下代码可以实现Hibernate自动生成表:

 
 
 
  1. package test;     
  2.      
  3. import java.io.File;     
  4.      
  5. import org.hibernate.HibernateException;     
  6. import org.hibernate.Session;     
  7. import org.hibernate.SessionFactory;     
  8. import org.hibernate.Transaction;     
  9. import org.hibernate.cfg.Configuration;     
  10. import org.hibernate.tool.hbm2ddl.SchemaExport;     
  11.      
  12. public class HibernateSchemaExport ...{     
  13.      
  14.     static Session session;     
  15.      
  16.     static Configuration config = null;     
  17.     static Transaction tx = null;     
  18.      
  19.     public static void main(String[] args) ...{     
  20.         /** *//**   
  21.           * 根据映射文件创建数据库结构   
  22.           */     
  23.         try ...{     
  24.              config = new Configuration().configure(new File(     
  25.                     "src/hibernate.cfg.xml"));     
  26.      
  27.              System.out.println("Creating tables...");     
  28.      
  29.              SessionFactory sessionFactory = config.buildSessionFactory();     
  30.              session = sessionFactory.openSession();     
  31.              tx = session.beginTransaction();     
  32.      
  33.              SchemaExport schemaExport = new SchemaExport(config);     
  34.              schemaExport.create(truetrue);     
  35.      
  36.              System.out.println("Table created.");     
  37.      
  38.              tx.commit();     
  39.      
  40.          } catch (HibernateException e) ...{     
  41.              e.printStackTrace();     
  42.             try ...{     
  43.                  tx.rollback();     
  44.              } catch (HibernateException e1) ...{     
  45.                  e1.printStackTrace();     
  46.              }     
  47.          } finally ...{     
  48.      
  49.          }     
  50.      }     
  51.      
  52. }  

【编辑推荐】

  1. Hibernate的三个状态(1)
  2. 扩展hibernate的查询
  3. 简单的Hibernate入门介绍
  4. Hibernate的三个状态(3)
  5. Hibernate的三个状态(2)

 

THE END