Skip to content
Related Articles

Related Articles

Hibernate – Annotations

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 18 Aug, 2022
View Discussion
Improve Article
Save 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 (Intellj)

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

XML




<?xml version="1.0" encoding="UTF-8"?>
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>org.example</groupId>
    <artifactId>Hibernateproject</artifactId>
    <version>1.0-SNAPSHOT</version>
 
    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.6.5.Final</version>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
 
    </dependencies>
 
</project>


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

hibernate.cfg.xml

XML




<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
<hibernate-configuration>
    <session-factory>
           
          <!--the path of database drivers-->
        <property name = "hibernate.connection.driver_class">
            com.mysql.cj.jdbc.Driver
        </property>
 
        <!-- Assume test is the database name -->
        <property name = "hibernate.connection.url">
            jdbc:mysql://localhost:3306/student
        </property>
         
          <!-- Your database username-->
        <property name = "hibernate.connection.username">
            root 
        </property>
 
        <property name = "hibernate.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>
 
        <!-- List of XML mapping files -->
          <!-- path of a mapping file, for us its our
             STudent class which is a POJO -->
        <mapping class="com.student.Student"/>
 
    </session-factory>
   
</hibernate-configuration>


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-

Annotations

Use of annotations

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

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.
@Column

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
@OrderBy

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

For example – we need to order by student first name in ascending order

@OrderBy(“firstName asc”) 

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

Student.java (POJO class)

Java




package com.student;
import javax.persistence.*;
 
// 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 students
@Table(name = "students")
public class Student {
    // @id make stuid as a primary key and @GeneratedValue
    // auto increment
    @Id
    @GeneratedValue
    // This will override and make column name id in place
    // of stuid
    @Column(name = "id")
    private int stuid;
    // This will override and make column name full name in
    // place of name
    @Column(name = "Full_name") private String name;
    // This will override and make column name Age in place
    // of age
    @Column(name = "Age") private int age;
    // This will override and make column name Department in
    // place of stream
    @Column(name = "Department") private String stream;
 
    //    Basic getters and setters to set and get values
    public int getStuid() { return stuid; }
 
    public void setStuid(int stuid) { this.stuid = stuid; }
 
    public String getName() { return name; }
 
    public void setName(String name) { this.name = name; }
 
    public int getAge() { return age; }
 
    public void setAge(int age) { this.age = age; }
 
    public String getStream() { return stream; }
 
    public void setStream(String stream)
    {
        this.stream = stream;
    }
}


Main.java (Action class)

Java




package com.student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
 
public class Main {
    public static void main(String[] args)
    {
 
        // Setting the objects
        Student s = new Student();
        s.setStuid(1);
        s.setName("Geek");
        s.setAge(22);
        s.setStream("Computer science");
 
        // activate hibernate network
        Configuration cfg = new Configuration();
 
        // We use sessionfactory to build a session for
        // database and hibernate
        SessionFactory factory
            = cfg.configure("hibernate.cfg.xml")
                  .buildSessionFactory();
 
        // 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(s);
 
        // commit is a transaction function used to push
        // some changes to database with reference to hql
        // query
        tx.commit();
 
        session.close();
    }
}


Output:

Output


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!