Annotations were introduced in Java 5, and since then most of the toolkits have started using them heavily. Annotations are decorators applied at the class and variable level that define the metadata about the class itself. Hibernate embraced annotations closely and integrated them with the core as first-class citizens. As they are a necessary tool in developing sophisticated ORM mappings, we will be learning about them in detail in this chapter. We’ll also discuss the pros and cons of using annotations versus traditional XML files toward the end of the chapter.
In earlier chapters, we worked with the mapping of persistent classes using XML files. Using XML files for our configuration and mapping has both advantages and disadvantages. For one thing, they are quite simple and easily readable, but they are also quite verbose and unfortunately do not impose type safety. Annotations, on the other hand, are quite concise and enable compile-type checks straightaway. They are metadata decorations applied directly on the class, therefore enabling the entities to be managed effectively. We discussed annotations briefly earlier, but now we’ll revisit and learn about them in detail.
As always, beginning with a simple example will help you on your path of learning annotations. Let’s start with a simple persistent class,
Employee, defined without annotations (pure POJO) here: