views:

69

answers:

4

I have seen many tutorials where the hibernate is implemented using annotations (basically hibernate annotations or JPA annotations). There are tutorial which mainly focuses on using the hibernate configuration files(hbm.xml files). No use of annotations at all.

Now I am little bit confused, which one is better approach ?

A: 

This depends on your likes. For example I prefer to annotate the classes for defining what are the primary keys, which values are autogenerated and what relationships the entities have. Also I use the configuration file persistence.xml in which I define how the entities are mapped to the database. So I seperated the programmer view of the domain model to the one of the database engineer.

coding.mof
A: 

I also prefer the annotation approach, because I like to see the classes and their database configurations in one place. This is on the other hand the biggest advantage of using configuration files: you don't need to touch the java classes.

splash
A: 

It's up to you! I don't think there is a better approach. Both solutions are dedicated to the same thing, i.e. help Hibernate to understand how your database is structured. Annotations have the advantage to be directly available in your Entity Java class file.

There was a time where XML was considered as a standard to define configuration information. Since Java 5, many information initially located in these XML files are now directly stored in the classes, using the annotations. For example, Spring 3.x framework or Java EE 6 now uses annotations.

romaintaz
+2  A: 

I definitely prefer to use annotations to define my mapping metadata. And actually, annotations are the approach recommend by Hibernate developers. Quoting Gavin King in More XML than code?

Of course, Hibernate Annotations has been around since early 2005 and there is no longer any good reason for people to define mappings in XML.

Pros:

  • annotations are typically less verbose
  • annotations live with the code, they are simpler to maintain (IMO)

Cons:

  • Changing metadata requires recompilation (if this is really an issue)

In other words, use annotations if you can. If you can't (you can't change the code, for example when working with legacy code), use XML mappings.

Pascal Thivent