Open In App

Hibernate – Annotations

Last Updated : 03 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

XML




  <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>
 
  <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>
     
    <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.6.14.Final</version>
    </dependency>
     
    <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 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 PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<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>


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 firstname 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.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:

 

 



Previous Article
Next Article

Similar Reads

Hibernate - Create Hibernate Configuration File with the Help of Plugin
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is a java framework that is used to develop persisten
3 min read
How to Create Your Own Annotations in Java?
Annotations are a form of metadata that provide information about the program but are not a part of the program itself. An Annotation does not affect the operation of the code they Annotate. Now let us go through different types of java annotations present that are listed as follows: Predefined annotations.: @Deprecated, @Override, @SuppressWarning
5 min read
Inherited Annotations in Java
Annotations in Java help associate metadata to the program elements such as classes, instance variables, methods, etc. Annotations can also be used to attach metadata to other annotations. These types of annotations are called meta-annotation. Java, by default, does not allow the custom annotations to be inherited. @inherited is a type of meta-anno
5 min read
Java @Retention Annotations
In Java, annotations are used to attach meta-data to a program element such as a class, method, instances, etc. Some annotations are used to annotate other annotations. These types of annotations are known as meta-annotations. @Retention is also a meta-annotation that comes with some retention policies. These retention policies determine at which p
3 min read
Java @Documented Annotations
By default, Java annotations are not shown in the documentation created using the Javadoc tool. To ensure that our custom annotations are shown in the documentation, we use @Documented annotation to annotate our custom annotations. @Documented is a meta-annotation (an annotation applied to other annotations) provided in java.lang.annotation package
2 min read
Java - @Target Annotations
Annotations in java are used to associate metadata to program elements like classes, methods, instance variables, etc. There are mainly three types of annotations in java: Marker Annotation (without any methods), Single-Valued Annotation (with a single method), and Multi-Valued Annotation (with more than one method). @Target annotation is a meta-an
3 min read
Spring Framework Annotations
Spring framework is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. Now talking about Spring Annotation, Spring Ann
5 min read
Spring Core Annotations
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. In the Spring framework, the annotations are classified into diffe
4 min read
Difference Between @Component, @Repository, @Service, and @Controller Annotations in Spring
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. Here, we are going to discuss the difference between the 4 most im
4 min read
Spring Boot Annotations - @JmsListener, @Retryable, @RSocketMessageMapping, @ConstructorBinding, and @Slf4j
Spring Boot is a popular framework for building modern, scalable, and efficient Java applications. One of the key features of Spring Boot is its extensive use of annotations, which simplify the process of configuring and deploying Spring-based applications. In this article, we will explore some of the latest Spring Boot annotations and how they can
7 min read
Spring Bean Validation - JSR-303 Annotations
In this article, we'll explore practical examples of how to apply JSR-303 annotations to your domain objects from basic annotations to advanced. So basically annotations provide a declarative way to configure Spring beans, manage dependencies, and define behaviors, reducing the need for boilerplate code and making your code more concise and express
6 min read
Annotations in Java
Annotations are used to provide supplemental information about a program. Annotations start with ‘@’.Annotations do not change the action of a compiled program.Annotations help to associate metadata (information) to the program elements i.e. instance variables, constructors, methods, classes, etc.Annotations are not pure comments as they can change
9 min read
Spring - Stereotype Annotations
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. Now talking about Spring Annotation, Spring Annotations a
10 min read
Spring Boot - Annotations
Spring Boot Annotations are a form of metadata that provides data about a spring application. Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead
8 min read
Spring Boot - @PathVariable and @RequestParam Annotations
When building RESTful APIs with Spring Boot, it's crucial to extract data from incoming HTTP requests to process and respond accordingly. The Spring framework provides two main annotations for this purpose: @PathVariable and @RequestParam. The @PathVariable annotation is used to retrieve data from the URL path. By defining placeholders in the reque
8 min read
Introduction to Hibernate Framework
Prerequisite : JDBC Need of Hibernate Framework Hibernate is used to overcome the limitations of JDBC like: JDBC code is dependent upon the Database software being used i.e. our persistence logic is dependent, because of using JDBC. Here we are inserting a record into Employee table but our query is Database software-dependent i.e. Here we are usin
4 min read
Hibernate - Cache Eviction with Example
Caching in Hibernate means storing and reusing frequently used data to speed up your application. There are two kinds of caching: Session-level and SessionFactory-level. Level 1 cache is a cache that stores objects that have been queried and persist to the current session. This cache helps to reduce the number of database round trips by storing obj
9 min read
Hibernate - Bag Mapping
For a multi-national company, usually, selections are happened based on technical questions/aptitude questions. If we refer to a question, each will have a set of a minimum of 4 options i.e each question will have N solutions. So we can represent that by means of "HAS A" relationship i.e. 1 question has 4 solutions. Via Bag Mapping, in Hibernate, w
4 min read
Difference between JDBC and Hibernate in Java
Java is one of the most powerful and popular server-side languages in the current scenario. One of the main features of a server-side language is the ability to communicate with the databases. In this article, let's understand the difference between two ways of connecting to the database (i.e.) JDBC and Hibernate. Before getting into the difference
2 min read
Hibernate Example using XML in Eclipse
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. In this article, let us see a Hibernate Example using XM
6 min read
Hibernate Lifecycle
Here we will learn about Hibernate Lifecycle or in other words, we can say that we will learn about the lifecycle of the mapped instances of the entity/object classes in hibernate. In Hibernate, we can either create a new object of an entity and store it into the database, or we can fetch the existing data of an entity from the database. These enti
4 min read
Java - JPA vs Hibernate
JPA stands for Java Persistence API (Application Programming Interface). It was initially released on 11 May 2006. It is a Java specification that gives some functionality and standard to ORM tools. It is used to examine, control, and persist data between Java objects and relational databases. It is observed as a standard technique for Object Relat
4 min read
Spring Boot - Integrating Hibernate and JPA
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Hibernate - Difference Between ORM and JDBC
Hibernate is a framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas Hibernate framework we use Objects to develop persistence logic that is independent of database software. ORM (Object-Relational Mapping) ORM, an abbreviation for Ob
4 min read
Hibernate - Generator Classes
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas in Hibernate framework we use Objects to develop persistence logic that is independent of
5 min read
Hibernate - Create POJO Classes
POJO stands for Plain Old Java Object. In simple terms, we use POJO to make a programming model for declaring object entities. The classes are simple to use and do not have any restrictions as compared to Java Beans. To read about POJO classes and Java Bean refer to the following article - POJO classes and Java Bean POJO is handier as its best in r
3 min read
Hibernate - One-to-One Mapping
Prerequisite: Basic knowledge of hibernate framework, Knowledge about databases, Java Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to
15 min read
Hibernate - SQL Dialects
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. An ORM(Object-relational mapping) framework simplifies data creation, data manipulation, and data access. It is a programming technique that maps the object to the d
3 min read
Hibernate - Web Application
A web application with hibernate is easier. A JSP page is the best way to get user inputs. Those inputs are passed to the servlet and finally, it is inserted into the database by using hibernate. Here JSP page is used for the presentation logic. Servlet class is meant for the controller layer. DAO class is meant for database access codes. Tools and
9 min read
Hibernate - Table Per Concrete Class using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
5 min read
three90RightbarBannerImg