2014-04-26 40 views
4

在休眠4.3 Ejb3Configuration類已被刪除。這個類通常用於從持久性單元(persistence.xml文件)到SchemaExport工具創建hibernate配置文件。如何使用SchemaExportTool與JPA和休眠4.3

作爲一個簡單的替代導出模式到SQL文件我使用以下代碼:

public static void export(String persistenceUnit, String exportFileName) { 
     Map<String, String> hash = new HashMap<String, String>(); 
     hash.put("hibernate.hbm2ddl.auto", "create-drop"); 
     EntityManagerFactory factory = Persistence.createEntityManagerFactory(
       persistenceUnit, hash); 
     org.hibernate.jpa.internal.EntityManagerFactoryImpl hibFactory = (org.hibernate.jpa.internal.EntityManagerFactoryImpl) factory; 
     SessionFactoryImpl hibSessionFactory = hibFactory.getSessionFactory(); 
     SchemaExport schema = ReflectUtils.getPrivateFieldValue(
       hibSessionFactory, "schemaExport"); 
     schema.setOutputFile(exportFileName); 
     schema.setFormat(false); 
     schema.setDelimiter(";"); 
     schema.drop(true, false); 
     schema.create(true, false); 
    } 

在這一段代碼,我基本上使用由HibernateSessionFactoryImpl創建的SchemaExport對象。缺點是每次執行時都會重新創建數據庫模式。有沒有其他簡單的方法與Hibernate 4.3和JPA一起使用SchemaExporTool?看來真正的問題是如何從persistenceunit創建Hibernate配置對象?

+0

的可能的複製[如何導出爲休眠模式> 4.3(HTTP:/ /stackoverflow.com/questions/22733631/how-to-export-the-schema-for-hibernate-4-3) – oers

+0

我寫了一個答案[這裏在stackoverflow](http://stackoverflow.com/a/372​​92442/ 644450),它不需要persistence.xml,也支持envers。 – oers

回答

1

我遇到了同樣的問題。我結束了通過使用Hibernate的內部PersistenceXmlParser persistence.xml文件中獲取信息和手動創建的配置對象:

public static void main(String[] args) { 

    PersistenceXmlParser parser = new PersistenceXmlParser(new ClassLoaderServiceImpl(), PersistenceUnitTransactionType.RESOURCE_LOCAL); 
    List<ParsedPersistenceXmlDescriptor> allDescriptors = parser.doResolve(new HashMap<>()); 

    for (ParsedPersistenceXmlDescriptor descriptor : allDescriptors) { 

     Configuration cfg = new Configuration(); 
     cfg.setProperty("hibernate.hbm2ddl.auto", "create"); 
     cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect"); 
     cfg.setProperty("hibernate.id.new_generator_mappings", "true"); 

     List<String> managedClassNames = descriptor.getManagedClassNames(); 
     for (String className : managedClassNames) { 
      try { 
       cfg.addAnnotatedClass(Class.forName(className)); 
      } catch (ClassNotFoundException e) { 
       System.out.println("Class not found: " + className); 
      } 
     } 

     SchemaExport export = new SchemaExport(cfg); 
     export.setDelimiter(";"); 
     export.setOutputFile("C:\\dev\\" + descriptor.getName() + "_create_schema.sql"); 
     export.setFormat(true); 
     export.execute(true, false, false, false); 

    } 
}