如何在JPA和Hibernate 4.3中使用SchemaExportTool

时间:2014-04-26 12:07:06

标签: java hibernate jpa hibernate-4.x

在Hibernate 4.3中删除了Ejb3Configuration类。此类通常用于从持久性单元(persistence.xml文件)到SchemaExport工具创建hibernate配置文件。

作为将模式导出到.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对象。缺点是每次执行时都会重新创建数据库模式。有没有其他简单的方法可以将SchemaExporTool与Hibernate 4.3和JPA一起使用?看来真正的问题是如何从persistenceunit创建Hibernate配置对象?

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题。我最后使用Hibernate的内部PersistenceXmlParser来访问persistence.xml文件中的信息并手动创建Configuration对象:

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);

    }
}