Open In App
Related Articles

Hibernate – Annotations

Improve Article
Save Article
Like Article

Annotation in JAVA is used to represent supplemental information. As you have seen @override, @inherited, etc are an example of annotations in general Java language. For deep dive please refer to Annotations in Java. In this article, we will discuss annotations referred to hibernate. So, the motive of using a hibernate is to skip the SQL part and focus on core java concepts. Generally, in hibernate, we use XML mapping files for converting our POJO classes data to database data and vice-versa. But using XML becomes a little confusing so, in replacement of using XML, we use annotations inside our POJO classes directly to declare the changes. Also using annotations inside out POJO classes makes things simple to remember and easy to use. Annotation is a powerful method of providing metadata for the database tables and also it gives brief information about the database table structure and also POJO classes simultaneously. 

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)


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

Step 2: Add the dependency to the pom.xml file

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.


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



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

Step 3: Add hibernate.cfg.xml file for database parameters

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



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        <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="">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>

The file should look like above

Step 4: Add POJO and main classes for working with the functionality

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


Use of annotations

@Entity  Used for declaring any POJO class as an entity for a database

Used to change table details, some of the attributes are-

  • name – override the table name
  • schema
  • catalogue
  • enforce unique constraints
@Id Used for declaring a primary key inside our POJO class
@GeneratedValue Hibernate automatically generate the values with reference to the internal sequence and we don’t need to set the values manually.

It is used to specify column mappings. It means if in case we don’t need the name of the column that we declare in POJO but we need to refer to that entity you can change the name for the database table. Some attributes are-

  • Name – We can change the name of the entity for the database
  • length – the size of the column mostly used in strings
  • unique – the column is marked for containing only unique values
  • nullable – The column values should not be null. It’s marked as NOT
@Transient Tells the hibernate, not to add this particular column
@Temporal This annotation is used to format the date for storing in the database
@Lob Used to tell hibernate that it’s a large object and is not a simple object

This annotation will tell hibernate to OrderBy as we do in SQL.

For example – we need to order by student firstname in ascending order

@OrderBy(“firstname asc”) 

These are some annotations that are mostly used in order to work with hibernate. (POJO class)


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
// By default hibernate will name the table Student as class
// name but @Table annotation override it to student
public class Student {
    private int id;
    private String firstName;
    private String city;
    public Student() {
    public Student(int id, String firstName, String city) {
        super(); = id;
        this.firstName = firstName; = city;
       //   Basic getters and setters to set and get values
    public int getId() {
        return id;
    public void setId(int 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) { = city;
    public String toString() {
        return "Student [id=" + id + ", firstName=" + firstName + ", city=" + city + "]";
} (POJO class)


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;
public class Address {
    // @id make address_id as a primary key and @GeneratedValue
    // auto increment
    private int addid;
    // This will override and make column length 50 in
    // place of street
    private String street;
      // This will override and make column name City in
    // place of City
    private String city;
    private boolean isOpen;
       // This will not create column name x in database
    private double x;
      // This will override and make column name date with specific Date format
    private Date date;
       //Lob to tell hibernate that image’s a large object and is not a simple object
    private byte[] images;
    public Address(int addid, String street, String city, boolean isOpen, double x, Date date, byte[] images) {
        this.addid = addid;
        this.street = street; = city;
        this.isOpen = isOpen;
        this.x = x; = date;
        this.images = images;
    public Address() {
        // 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) { = 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) { = date;
    public byte[] getImages() {
        return images;
    public void setImages(byte[] images) {
        this.images = images;
    public String toString() {
        return "Address [addid=" + addid + ", street=" + street + ", city=" + city + ", isOpen=" + isOpen + ", x=" + x
                + ", date=" + date + ", images=" + Arrays.toString(images) + "]";
} Class)


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");
        //creating object of class
        Address address= new  Address();
        address.setDate(new Date());
       // 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;;
       // commit is a transaction function used to push
       // some changes to database with reference to hql
       // query




Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 03 Jan, 2023
Like Article
Save Article
Similar Reads
Complete Tutorials