Sunday, 10 May 2009

Hibernate Annotations : A powerful addition to the Hibernate family.

I recently used Hibernate Annotations in a project and was impressed by the power and relative flexibility offered by annotations and the difference it made with regards to cleaning up the project build. While the major advantage of using annotations was that I could completely get rid of the hibernate mapping xmls, it also made life easier when it came to specifying relationships between my entity beans.

To get started with Hibernate Annotations, follow the Hibernate learning trail and download the required jars and set up your project. If you are using Maven, you can specify the dependencies in a Maven POM as outlined in this example. Once you have a project set up, take a look at this reference guide. Mapping entity bean associations and relationships is simple and this is a good example that demonstrates the annotation entries for mapping different relationships. One major advantage of using Annotations is that several mappings and associations can be configured by default. For example, if I defined a primary key mapping of an entity bean to a database as follows:
@Id
public Long getId() {
return id;
}
and left out @GeneratedValue(strategy=GenerationType.AUTO)

Hibernate would assume that the application will provide the Primary Key or in other words, the strategy for the primary key, if I were to specify the same in an hbm file would be equivalent to "assigned". Similarly, If the Annotation @Table(name="EMPLOYEE") on a bean can be used to map the bean to the table EMPLOYEE but if not given, the name of the bean would be used as a key by Hibernate for mapping the table to a bean.

Thus, Hibernate Annotations reduces the setup time in adding Hibernate to a project while simplifying the maintenance of the associated code.

No comments: