Chapter 3. Annotations
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.
Working Through an Example
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:
publicclassEmployee{privateintid=0;privateStringname=null
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access