Hibernate - Annotations

Last Updated : 9 Apr, 2026

Annotations in Java provide additional metadata to classes and methods. In Hibernate, annotations are used to replace XML mapping files, making it easier to map POJO classes to database tables and focus on core Java instead of SQL.

  • Provides extra information about classes and database structure.
  • Eliminates the need for complex XML mapping files.
  • Maps POJO classes directly to database tables using annotations.
  • Allows developers to focus more on Java logic.

Setting up the Hibernate Annotations Project

It's recommended to set up the Maven project for hibernate because it becomes easy to copy-paste dependency from the official Maven repository into your pom.xml.

Step 1: Create Maven Project (Eclipse)

  • Open Eclipse ->File ->New ->Maven Project
  • Click Next ->Enter project name -> Finish
Image
 

Go to next and name a project and click to finish.

Step 2: Add the dependency

After setting up a maven project, by default, you get a POM.xml file which is a dependency file. POM stands for project object model, which allows us to add or remove dependency from 1 location.

Image
 

The project structure and pom.xml should look like this. Now, add hibernate and MySQL dependency to use annotations to create a table and to use HQL(hibernate query language).

pom.xml file

XML
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.spring.hibernate</groupId>
  <artifactId>Spring-Hibernate</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Spring-Hibernate</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.6.14.Final</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
    <dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.0.31</version>
    </dependency>
  </dependencies>
</project>

Make sure you add dependency and it should look like the above file.

Step 3: Add hibernate.cfg.xml file

We use the hibernate.cfg.xml file to provide all related database parameters like database username, password, localhost, etc. Make sure you make the hibernate.cfg.xml inside the resource folder.

hibernate.cfg.xml

XML
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernatedemo</property>
        <property name="connection.username">root</property>
        <property name="connection.password">your password</property>
         <!-- We use dialect to provide information about which
            database we are using, we are using mysql -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
         <!-- This property enables us to update the
               table everytime the program runs-->
        <property name="hbm2ddl.auto">update</property>
        <property name="show_sql">true</property>
        
         <!-- List of XML mapping files -->
          <!-- path of a mapping file, for us its our
             Student class and Address class which is a POJO -->
        <mapping class="com.spring.hibernate.Student"></mapping>
        <mapping class="com.spring.hibernate.Address"></mapping>

    </session-factory>
</hibernate-configuration>

Step 4: Add POJO and main classes

Here are some annotations used in our POJO specifically for hibernate-

AnnotationUse
@EntityDeclares a POJO class as a database entity
@TableSpecifies table details (name, schema, constraints)
@IdMarks primary key field
@GeneratedValueAuto-generates primary key values
@ColumnMaps class field to table column (name, length, unique, nullable)
@TransientIgnores field (not stored in database)
@TemporalFormats date/time values
@LobUsed for large objects (BLOB/CLOB)
@OrderBySorts data (like SQL ORDER BY)

These are some annotations that are mostly used in order to work with hibernate.

Student.java (POJO class)

Java
package com.spring.hibernate;


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

// Entity is declare to make this class an object for the
// database
@Entity

// By default hibernate will name the table Student as class
// name but @Table annotation override it to student
@Table(name="student")
public class Student {
    
    @Id
    private int id;
    private String firstName;
    private String city;
    
    public Student() {
        super();
        
    }

    public Student(int id, String firstName, String city) {
        super();
        this.id = id;
        this.firstName = firstName;
        this.city = city;
    }

       //   Basic getters and setters to set and get values

    public int getId() {
        return id;
    }

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

    

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", firstName=" + firstName + ", city=" + city + "]";
    }

    
}

Address.java (POJO class)

Java
package com.spring.hibernate;

import java.util.Arrays;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

@Entity
@Table(name="address")
public class Address {
    // @id make address_id as a primary key and @GeneratedValue
    // auto increment
    @Id
    @GeneratedValue
    @Column(name="address_id")
    private int addid;
  
    // This will override and make column length 50 in
    // place of street
    @Column(length=50)
    private String street;
  
      // This will override and make column name City in
    // place of City
      @Column(name="city")
    private String city;
  
    private boolean isOpen;
  
       // This will not create column name x in database
       @Transient
    private double x;
       
      // This will override and make column name date with specific Date format
    @Temporal(TemporalType.DATE)
    private Date date;
    
       //Lob to tell hibernate that image’s a large object and is not a simple object
    @Lob
    private byte[] images;
    
    public Address(int addid, String street, String city, boolean isOpen, double x, Date date, byte[] images) {
        super();
        this.addid = addid;
        this.street = street;
        this.city = city;
        this.isOpen = isOpen;
        this.x = x;
        this.date = date;
        this.images = images;
    }
    public Address() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public int getAddid() {
        return addid;
    }
    public void setAddid(int addid) {
        this.addid = addid;
    }
    public String getStreet() {
        return street;
    }
    public void setStreet(String street) {
        this.street = street;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public boolean isOpen() {
        return isOpen;
    }
    public void setOpen(boolean isOpen) {
        this.isOpen = isOpen;
    }
    public double getX() {
        return x;
    }
    public void setX(double x) {
        this.x = x;
    }
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
    public byte[] getImages() {
        return images;
    }
    public void setImages(byte[] images) {
        this.images = images;
    }
    @Override
    public String toString() {
        return "Address [addid=" + addid + ", street=" + street + ", city=" + city + ", isOpen=" + isOpen + ", x=" + x
                + ", date=" + date + ", images=" + Arrays.toString(images) + "]";
    }

}

Main.java(Main Class)

Java
package com.spring.hibernate;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Project Started" );
       
        // We use sessionfactory to build a session for
        // database and hibernate
        SessionFactory factory = new Configuration().configure().buildSessionFactory();
         
        //creating object of student
        Student student= new Student(102,"xyz","pune");
        System.out.println(student);
         
        
        //creating object of class
        
        Address address= new  Address();
        address.setStreet("JBRoad");
        address.setCity("Pune");
        address.setDate(new Date());
        address.setX(34.8);
        address.setOpen(true);
        
        
       // opening a session
       Session session = factory.openSession();
       // Transaction is a java object used to give the
       // instructions to database
       Transaction tx=session.beginTransaction();
         // we use save to provide the object to push in
       // database table
       session.save(student);
       session.save(address);
       // commit is a transaction function used to push
       // some changes to database with reference to hql
       // query
       tx.commit();
       session.close();
    }
}

Output:

Image
 
Image
Comment