gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:17:21 25 4
gpt4 key购买 nike

我有一个使用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com