Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate : mapping files or annotations?

Tags:

java

hibernate

As I started working with Hibernate a few days ago, I was just wondering : suppose you're starting a project from scratch. Would you use annotation-based mapping or Hibernate mapping files, to generate the database schema.

It is my understanding that Hibernate mapping files offer some features that you won't find (at least, not the exact equivalent) with annotations. But still, I have the feeling that nowadays, projects using Hibernate would rather go for annotation-based than Hibernate mapping files.

Has anybody ever chosen mapping files over annotations, and if so, for what reasons?

like image 388
kyiu Avatar asked Apr 17 '12 12:04

kyiu


2 Answers

What advantages I see in using @Annotations:

  • compiler-safe
  • based on @Entity you can easily distinguish entity from no-entity
  • with packagesToScan Spring's feature entites are easily scannable
  • moving entites from packages to packages or class renaming is easy

What advantages I see in using XML:

  • it does not litters java classes with unnecessary vendor-specific annotations (imagine java model class with JPA, JAXB, SOLRJ annotations)
  • configuration in one place
  • easier to maintain as a whole

We use annotations, but keep XML as an option.

like image 154
JMelnik Avatar answered Oct 21 '22 12:10

JMelnik


Go ahead with annotations any day. The XML configurations where really over used and saving the metadata inside the class is a good viable option.

Annotations will help you map the relationships better and it will align you to the JPA standard as hibernate uses mostly JPA annotations. There are no real problems using annotations and there is not much trade-off either. It has superior advantages over the XML based configurations. There might be few hacks missing when you use annotations but they will come along.

It is even possible to use annotations for new classes in a legacy project that has XML based mapping as told here.

like image 29
ManuPK Avatar answered Oct 21 '22 11:10

ManuPK