jpa oracle schema,如何在JPA和Hibernate 4.3中使用SchemaExportTool

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

作为将模式导出到.sql文件的简单替代方法,我使用以下代码:

public static void export(String persistenceUnit, String exportFileName) {

Map hash = new HashMap();

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一起使用?似乎真正的问题是如何从持久性单元创建Hibernate配置对象?

最佳答案

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

public static void main(String[] args) {

PersistenceXmlParser parser = new PersistenceXmlParser(new ClassLoaderServiceImpl(), PersistenceUnitTransactionType.RESOURCE_LOCAL);

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值