Javatpoint Logo

91-9990449935

 0120-4256464

Javatpoint Logo

Hibernate with Annotation

The hibernate application can be created with annotation. There are many annotations that can be used to create hibernate application such as @Entity, @Id, @Table etc.

Hibernate Annotations are based on the JPA 2 specification and supports all the features.

All the JPA annotations are defined in the javax.persistence.* package. Hibernate EntityManager implements the interfaces and life cycle defined by the JPA specification.

The core advantage of using hibernate annotation is that you don't need to create mapping (hbm) file. Here, hibernate annotations are used to provide the meta data.


Example to create the hibernate application with Annotation

There are 4 steps to create the hibernate application with annotation.

  1. Add the jar file for oracle (if your database is oracle) and annotation
  2. Create the Persistent class
  3. Add mapping of Persistent class in configuration file
  4. Create the class that retrieves or stores the persistent object

1) Add the jar file for oracle and annotation

For oracle you need to add ojdbc14.jar file. For using annotation, you need to add:

  • hibernate-commons-annotations.jar
  • ejb3-persistence.jar
  • hibernate-annotations.jar

2) Create the Persistent class

Here, we are creating the same persistent class which we have created in the previous topic. But here, we are using annotation.

@Entity annotation marks this class as an entity.

@Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name bydefault.

@Id annotation marks the identifier for this entity.

@Column annotation specifies the details of the column for this property or field. If @Column annotation is not specified, property name will be used as the column name bydefault.

Employee.java


3) Add mapping of Persistent class in configuration file

open the hibernate.cgf.xml file, and add an entry of mapping resource like this:

Now the configuration file will look like this:

hibernate.cfg.xml


4) Create the class that retrieves or stores the persistent object

In this class, we are simply storing the employee object to the database. Here, we are using the AnnotationConfiguration class to get the information of mapping from the persistent class.





Latest 4 Tutorials on JavaTpoint