O'Reilly logo

Just Hibernate by Madhusudhan Konda

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

public class Employee {
  private int id =0;
  private String name = null

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required