如何将Hibernate SchemaUpdate类与JPA persistence.xml一起使用?

Joh*_*zzo 17 hibernate jpa persistence.xml

我有一个使用SchemaUpdate的主方法在控制台上显示要更改/创建的表,它在我的Hibernate项目中工作正常:

 public static void main(String[] args) throws IOException {
  //first we prepare the configuration
  Properties hibProps = new Properties();
  hibProps.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jbbconfigs.properties"));
  Configuration cfg = new AnnotationConfiguration();
  cfg.configure("/hibernate.cfg.xml").addProperties(hibProps);

  //We create the SchemaUpdate thanks to the configs
  SchemaUpdate schemaUpdate = new SchemaUpdate(cfg);


  //The update is executed in script mode only
  schemaUpdate.execute(true, false);
  ...  
Run Code Online (Sandbox Code Playgroud)

我想在JPA项目中重用此代码,没有hibernate.cfg.xml文件(也没有.properties文件),而是一个persistence.xml文件(在JPA规范中指定的META-INF目录中自动检测) .

我尝试过这么简单的改编,

Configuration cfg = new AnnotationConfiguration();
cfg.configure();
Run Code Online (Sandbox Code Playgroud)

但是那个例外失败了.

Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found
Run Code Online (Sandbox Code Playgroud)

有人这样做过吗?谢谢.

Pet*_*raf 7

卡里姆走在正确的轨道上,但让我试着澄清一下.

假设你有一个没有Hibernate特定的vanilla JPA标准配置,除了类路径上的Hibernate jar.如果您在J2SE引导程序模式下运行,那么您已经有了一些看起来像这样的代码,无论是Java还是Spring配置等:

Map<String, Object> props = getJPAProperties();
EntityManagerFactory emf = 
    Persistence.createEntityManagerFactory("persistence-unit-name", props);
Run Code Online (Sandbox Code Playgroud)

要运行SchemaUpdate,只需使用它:

Map<String, Object> props = getJPAProperties();
Ejb3Configuration conf = 
    new Ejb3Configuration().configure("persistence-unit-name", props);
new SchemaUpdate(conf.getHibernateConfiguration()).execute(true, false);
Run Code Online (Sandbox Code Playgroud)

我不确定它如何在容器环境中运行,但在简单的J2SE或Spring类型的配置中,这就是它的全部内容.