hibernate - 如何在JPA persistence.xml中使用Hibernate SchemaUpdate类?

标签 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);
  ...  


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

我尝试了这种过于简单的调整,

Configuration cfg = new AnnotationConfiguration();
cfg.configure();


但由于该异常而失败。

Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found


有人做过吗?
谢谢。

最佳答案

卡里姆(Kariem)走在正确的道路上,但让我尝试澄清一下。

假设您具有普通的JPA标准配置,除了classpath上的Hibernate jars外,没有任何Hibernate特定的配置。如果您以J2SE引导模式运行,那么您已经有一些类似于Java或Spring配置的代码,如下所示:

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


要运行SchemaUpdate,只需使用以下代码即可:

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


我不确定这在容器环境中如何运行,但是在简单的J2SE或Spring类型的配置中,仅此而已。

关于hibernate - 如何在JPA persistence.xml中使用Hibernate SchemaUpdate类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2645255/

相关文章:

java - 如何在 Hibernate 注解中创建 Tinyint Field

java - Hibernate 查询在论坛问题中搜索内容

java - 如何让EhCache重置一个域与其他域之间的一对多关系的缓存?

oracle - JPA根据请求参数更改实体表名称

java - maven-antrun-plugin 跳过执行

java - 具有 3 个表和复合主键的定义问题 JPA

Hibernate Cascade PERSIST

java - 在 Spring Data JPA 存储库中使用泛型

java - 没有名为 EntityManager 的持久性提供程序...错误

Eclipse - 如何修复错误 "No persistence.xml file found in project"JPA 问题