views:

52

answers:

2

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.xml and 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.

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

+2  A: 

hibernate.cfg.xml is for Hibernate; persistence.xml is for JPA.

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

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.)

duffymo
@duffymo, and I have to duplicate parameters in both files?
Vincenzo
+2  A: 

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.

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

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

References

Pascal Thivent
@Pascal, thanks for the explanation. I'm also using `hibernate3:hbm2ddl` and I think that it needs `hibernate.cfg.xml`, right? And I feel that it doesn't know how to work with `persistence.xml`. Am I right? I need two files in this case? (I'm working ONLY with JPA)
Vincenzo
@Vincenzo According to [this article](http://users.mafr.de/~matthias/articles/generating-ddl-scripts.html), `hibernate3:hbm2ddl` can be used with a `jpaconfiguration` and a `persistence.xml`. So no, you don't need an `hibernate.cfg.xml`.
Pascal Thivent
@Pascal Many thanks!
Vincenzo