Why do we use hibernate annotation?

2019-04-07 18:45发布

问题:

Why is it important? what are advantage according to XML mapping? Can you explan these? thank you.

回答1:

It is not something important as in "mandatory". It's a different possibility, with strength and weaknesses.

Advantages:

  • Compile-time checking : writing in Java (instead of Xml) is very user-friendly in the IDE nowadays. No more typos discovered when starting your application (incremental compilation), not that much to remember (completion)...
  • Localized with the code (class level) : instead of having to open two files (java and xml) to get the full story, with one annotated java file, you open only one file. This is less repetitive, faster in the long run.
  • Localized with the code (method or field level) : because the annotation go on a method (or field), there is no need to specify the method it belongs to. That redondant information is not given, which is shorter, and always coherent (even after a code refactoring for example). Maintenance is so much faster.
  • Tools (javadoc, other tools using reflection) can use the annotations for some other requirements.
  • Annotations are newer than the xml, the team used the input they had received at the time to provide better default values. Xml has some, but can't change much for compatibility reasons. Often, with the annotations technology, you write no annotation at all, and it works. Imagine the time-saving, especially during development.


回答2:

I don't understand all the hype around annotation and I prefer HBM for the following reasons (These reasons overrule the disadvantages like typos, compile time check for me):

  1. Seperation od concerns/Single responsibility: With HBM's you have all the ORM related stuff in HBM. Entity and domain logic (independent of table structure) in java class. Your DB and java class can be changed independently (Only HBM needs to be updated).
  2. Your code is not cluttered with annotation. I prefer to just look at domain logic. Annotations add a lot of noise.

If HBMs are well organized (one HBM per java class, consistent naming) it becomes easy to navigate between the two. Junit test and some discipline will remove the need for compile time check. As for defaults, I think if hibernate can work no annotaions at all it should be able to work with no XML at all (conceptually - dont know if this is reality)