Java Hibernate 的两个配置文件的目的是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3807503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 05:20:39  来源:igfitidea点击:

what is the purpose of two config files for Hibernate?

javahibernatemaven-2

提问by yegor256

This is my current project structure:

这是我目前的项目结构:

pom.xml
/src
  /main
    /resources
      hibernate.cfg.xml
      /META-INF
        persistence.xml

I have very similar configuration params in both files (hibernate.cfg.xmland persistence.xml), which looks strange, but this is what I saw in many online examples and tutorials. I can't understand why do I need to have two files. Is it possible to work just with one? Please explain.

我在两个文件 (hibernate.cfg.xmlpersistence.xml) 中都有非常相似的配置参数,这看起来很奇怪,但这是我在许多在线示例和教程中看到的。我不明白为什么我需要两个文件。是否可以只与一个一起工作?请解释。

ps. For example, should I declare hibernate.dialectin both files, or just one will be enough? If so, which one to use?

附:例如,我应该hibernate.dialect在两个文件中声明,还是只有一个就足够了?如果是这样,使用哪一种?

采纳答案by Pascal Thivent

If you are using Hibernate's proprietary API, you'll need the hibernate.cfg.xml. If you are using JPA i.e. Hibernate EntityManager, you'll need the persistence.xml.

如果您使用 Hibernate 的专有 API,则需要hibernate.cfg.xml. 如果您使用的是 JPA,即 Hibernate EntityManager,您将需要persistence.xml.

So you generally don't need both as you use eitherHibernate proprietary API or JPA.

所以,你通常你用不用这两个无论是Hibernate的专有API或者JPA。

However, if you were usingHibernate Proprietary API and already have a hibernate.cfg.xml(and hbm.xmlXML mapping files) but want to start using JPA, you can reuse the existing configuration files by referencing the hibernate.cfg.xmlin the persistence.xmlin the hibernate.ejb.cfgfileproperty - and thus have both files. Reusing existing hbm.xmlfiles is IMO a realistic scenario that could justify keeping both (even if I'd probably migrate to JPA annotations on the long run).

不过,如果你是使用Hibernate的专有API,而且已经有hibernate.cfg.xml(和hbm.xmlXML映射文件),但希望开始使用JPA,您可以通过引用重用现有的配置文件hibernate.cfg.xmlpersistence.xmlhibernate.ejb.cfgfile财产-因此拥有这两个文件。重用现有hbm.xml文件是 IMO 一个现实的场景,可以证明同时保留两者(即使从长远来看我可能会迁移到 JPA 注释)。

References

参考

回答by duffymo

hibernate.cfg.xmlis for Hibernate; persistence.xmlis for JPA.

hibernate.cfg.xml用于休眠;persistence.xml用于 JPA。

If you do Hibernate without JPA, you don't need the latter.

如果您在没有 JPA 的情况下执行 Hibernate,则不需要后者。

If you do JPA, you have to have a provider implementation, which means Hibernate, EclipseLink, etc. (There may be other legit JPA implementations, but I don't have time to check right now.)

如果你做 JPA,你必须有提供者实现,这意味着 Hibernate、EclipseLink 等(可能还有其他合法的 JPA 实现,但我现在没有时间检查。)