Is there a good reason to configure hibernate with XML rather than via annotations? Is there a good reason to configure hibernate with XML rather than via annotations? xml xml

Is there a good reason to configure hibernate with XML rather than via annotations?


I think it's pretty safe to say that you're not missing out on anything.

If there are any capabilities in XML that can't be represented in attributes (and I believe there are some rare cases) then you still have the option to use [RawXml] and write the XML in the attribute. So you can't possibly miss out on any functionality.

It might make sense to use XML if you have enough programmers in your team who simply prefer to manage separate files or if there is a genuine need to edit xml mappings on the fly. Xml mapping files are probably easier to manipulate for very complex mapping and they can contain useful information (comments on fetching strategies etc).

There is also the issue of architecture, where some people argue that separating the mapping into XML files provides a better separation between business-related code and instructions on how it is persisted.


Annotations are a great way to quickly configure Hibernate. But one of the key features of OR mappers like Hibernate is that you keep your domain model "persistence ignorant" your objects don't need to know anything about where and how they are persisted. Some may argue that using annotations breaks that. And in situations where persistence is just one of many concerns it makes sense to keep things separate.

Another reason can be that domain objects are persisted differently in different situations, you can have multiple databases used by one application or even more applications that use the same domain model.


Doesn't Hibernate use the EJB3/JPA standard annotations? If so, I can think of at least one reason to use XML: those annotations don't have all the capabilities of Hibernate.

Example: Hibernate can define a "native" type for IDs. This will create an auto-increment field on MySQL and a sequence on Oracle. There's no way to do this with JPA annotations that'll work in both situations.

Also, XML is pluggable. Annotations aren't. This might matter for you if you ship to multiple database platforms and have different config for each one.

XML has fallen out of favour with a lot of developers and for that reason alone I think a lot favour annotations. Thing is, you have XML anyway (in the form of a persistence.xml file and possibly others). It's a bit like six of one, half a dozen of the other.