How to use Annotation in Hibernate?

In the previous article, we have seen What is Association mapping. You can check it here. In this article, we will cover How to use Annotation in Hibernate?

Until now, We have used the XML file for mapping classes to database. Now, instead of using XML, we will use Annotation in Hibernate.

What is Annotation?

Annotation in a simple term is extra information added to the document. It can be a comment or a note. In Today’s programming world annotation has replaced the traditional pattern of writing programs.

What is Hibernate Annotation?

Hibernate Annotation helps us to provide more information about the object and table.

  • Hibernate Annotations are created on the JPA2 (Java Persistent API) specification.
  • It is present in javax.persistence package.
  • Hibernate Annotations are provided in persistent classes.
  • It is used to provide the metadata.

How to use Annotation in Hibernate?

We have to use annotation in a persistent class. Let’s see the annotation that will be used

  • @Entity: This annotation is present in javax.persistence package. This implies the bean class to be used as an entity.
  • @Table: This annotation is present in javax.persistence package. This implies the table where our bean class will be persisted.
  • @Id: This annotation is present in javax.persistence package. To indicate the primary key we use this annotation. It generates the default value.
  • @Column: This annotation is present in javax.persistence package. This indicates the column present in the table where our attributes from the persistent class are mapped. It takes four attributes such as name, length, nullable, unique.
  • @GeneratedValue: This annotation is present in javax.persistence package. This generates the primary key automatically. It has four attribute-AUTO, IDENTITY, SEQUENCE, TABLE. 

Example of creating the annotation-based class

Note: Your JDK version should be JDK 5.0. In order to use annotation download the jar file from https://sourceforge.net/projects/hibernate/files/hibernate-annotations/here.

Create Database Device

<------Create database Device--------->
mysql>create database device;
<-----Use database device------------->
mysql>use device;
<----Create Table device_table-------->
mysql>CREATE TABLE `device_table` (
  `id` int NOT NULL AUTO_INCREMENT,
  `device_name` varchar(45) DEFAULT NULL,
  `device_company` varchar(45) DEFAULT NULL,
  `device_code` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ;

Create Annotation-based Persistent class-Device.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "device_table")
public class Device {
  @Id
  @Column(name = "id")
  private int id;

  @Column(name = "device_name")
  private String deviceName;

  @Column(name = "device_company")
  private String deviceCompany;

  @Column(name = "device_code")
  private int deviceCode;

  public Device() {
    super();
    // TODO Auto-generated constructor stub
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getDeviceName() {
    return deviceName;
  }

  public void setDeviceName(String deviceName) {
    this.deviceName = deviceName;
  }

  public String getDeviceCompany() {
    return deviceCompany;
  }

  public void setDeviceCompany(String deviceCompany) {
    this.deviceCompany = deviceCompany;
  }

  public int getDeviceCode() {
    return deviceCode;
  }

  public void setDeviceCode(int deviceCode) {
    this.deviceCode = deviceCode;
  }

}

Create hibernate.cfg.xml file

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">

<hibernate-configuration>

  <session-factory>
    <property name="hbm2ddl.auto">update</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/device</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <mapping class="Device"/>
  </session-factory>

</hibernate-configuration>

Create TestClass.java

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class TestClass {

  public static void main(String[] args) {
    Device device = new Device();
    device.setDeviceName("Mobile");
    device.setDeviceCompany("Samsung");
    device.setDeviceCode(5695);
    SessionFactory factory = new Configuration().configure().buildSessionFactory();
    Session session = factory.openSession();
    session.beginTransaction();
    session.persist(device);
    System.out.println("added");
    session.getTransaction().commit();
  }
}

Output

mysql> select * from device_table;
+----+-------------+----------------+-------------+
| id | device_name | device_company | device_code |
+----+-------------+----------------+-------------+
|  1 | Mobile      | Samsung        |        5695 |
+----+-------------+----------------+-------------+
2 rows in set (0.13 sec)

Thus this is how we create an annotation-based class in Hibernate.

In the next article of this tutorial, we will see HQL(Hibernate Query Language) and its advantages.