Hibernate Annotation with Example

Hibernate is an ORM (Object-Relational Mapping) tool which simplifies the application development. Hibernate provides a framework which interacts with the data stored in the databases and it also uses the specifications of the Java Persistence API (JPA).

Hibernate provides Annotations for the ease of web development. Without using hibernate-mapping file, you can map a java class to the corresponding table with the help of JPA Annotations. Some of the JPA Annotations are listed below:

i. @Entity- It is used for making a bean class an entity bean, so it must contain a no-arg constructor.

ii. @Table- It is used to create a table for the annotated entity.

iii.@Id- The primary key in the table is denoted as @Id.

iv.@Generatedvalue- It is used to auto-generate the value of the @Id field.

v.@Column- It is used to define the details of the column to which an attribute is mapped.

  1. Add Dependencies

When using hibernate annotations, you need to add dependencies in pom.xml. Add dependencies between <dependencies>...</dependecies> tag. Some dependencies are listed below:


  org.hibernate
  hibernate-core
  5.3.1.Final>/version>
 
 
  org.hibernate
  hibernate-validator
  6.0.17.Final
  

You need to add Oracle dependency manually. If you are using Mysql, then you need to add MySQL jar or dependency.

2. Create a POJO/ Bean/ Persistence class

The encapsulation of many objects into a single object is done by POJO class or Bean class.

All the variables of bean class are set as private with public setter and getter methods.

Here we use Annotations in the bean class.

Bean class-Book.java

 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.GeneratedValue;
 import javax.persistence.GenerationType;
 import javax.persistence.Id;
 import javax.persistence.Table;
 @Entity
 @Table(name="Book01")
 public class Book {
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private int bno;
  @Column(name="bname")
  private String bname;
  @Column(name="price")
  private int price;
  public int getBno() {
  return bno;
  }
  public void setBno(int bno) {
  this.bno = bno;
  }
  public String getBname() {
  return bname;
  }
  public void setBname(String bname) {
  this.bname = bname;
  }
  public int getPrice() {
  return price;
  }
  public void setPrice(int price) {
  this.price = price;
  }
  } 

3. Create a Configuration File

The name for configuration file should be hibernate.cfg.xml. It contains information about the mapping file and relational database.

hibernate.cfg.xml

   
  
  
  
    
  
        update  
        org.hibernate.dialect.MySQL5Dialect

        jdbc:mysql://localhost:3306
/test2
        com.mysql.jdbc.Driver

        root  
        root   
        true
        
     

      
 

4. Create the Application Class

    It is a class which contains the main() method used to run the application.

    Let’s create AppTest.java.

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

public class AppTest 
{
public static void main( String[] args )
{
Configuration  cfg= new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory fact = cfg.buildSessionFactory();
Session sess= fact.openSession();
sess.beginTransaction();
        
Book book=new Book();
book.setBno(401);
book.setBname("Java Complete Reference");
book.setPrice(550);
             
sess.save(book);  
sess.getTransaction().commit();  
System.out.println("saved successfully ");    
sess.close();      
    }
} 
Annonation Hibernate

Table-Book01

hibernate annonation

Related Topics

Hibernate Inheritance Joined Table

In this inheritance strategy, mapping of the child class fields is done with the common fields of the parent class in a separate table. In other words, the common entities between the child...

3 minutes read.

Hibernate Annotation with Example

Hibernate is an ORM (Object-Relational Mapping) tool which simplifies the application development. Hibernate provides a framework which interacts with the data stored in the databases and it also uses the specifications of the...

2 minutes read.

Hibernate Mapping

Hibernate Mapping Association- It means that two or more things are related to each other by some specific relation. In other words, it specifies how the objects are associated with each other. Hibernate mapping is one...

2 minutes read.

Hibernate One-to-One Mapping Example

One-to-One Hibernate Mapping In One-to-One association mapping, one object of a persistent class is related to one object of another persistent class. Here, we are going to create an example of one-to-one mapping using...

3 minutes read.

Hibernate Caching

What is Caching? Caching is a process of saving data into the cache memory. A cache is a temporary storage layer which is used to increase the speed of data access. It allows...

2 minutes read.

Hibernate Inverse

Hibernate Inverse An Inverse attribute is used to maintain the relationship between the parent and child class object. The inverse attribute is used only with bi-directional mappings such as one-to-many and many-to-many Hibernate mapping. In Hibernate, the...

2 minutes read.

Dirty Checking in Hibernate

Dirty checking is an essential concept of Hibernate. The Dirty checking concept is used to keep track of the objects. It automatically detects whether an object is modified (or not) or wants to...

6 minutes read.

Hibernate First-Level Cache

The first-level cache is related to the Session object. First level cache objects of one Session are not visible to the other Sessions, and all the cache data is lost when the Session...

2 minutes read.

Hibernate N+1 Select Problem

Hibernate N + 1 Select Problem The N + 1 Select problem is a performance issue in Hibernate. In this problem, a Java application makes N + 1 database calls (N = number...

4 minutes read.

Hibernate Lifecycle

Hibernate Lifecycle In Hibernate, the mapped instances of the entity classes have a lifecycle. Either we can create a new object, or we can fetch the existing data from the database. The value objects do...

3 minutes read.

Hibernate One-to-Many Mapping

One-to-Many Hibernate Mapping Example In One-to-many association mapping, only one object of a persistent class is related to many objects of another persistent class. It is a relationship in which one (parent) is related...

3 minutes read.

Hibernate get() vs. load()

Hibernate methods, get() and load() both are provided by the Session interface and used to retrieve the objects from the database. Session.get() The session.get() method is used to fetch a persistent object of the...

2 minutes read.

Hibernate Tutorial

What is Hibernate? Hibernate is an Object-Relational Mapping (ORM) tool which reduces the difficulty in the application development. Hibernate provides a framework that interacts with the data stored in the databases. It also uses...

3 minutes read.

Hibernate Named Query using Annotation

In annotation-based named query, we use @NamedQuery annotation inside the POJO class. @NamedQuery- It is used to describe a single named query. It consists of four attributes- two of which are compulsory, and...

2 minutes read.

Hibernate History and Versions

Next → History of Hibernate Hibernate was developed in 2001 by Gavin king with his colleagues from Circus Technologies. The main aim was to provide better persistence capabilities than those of EJB2, by reducing the...

2 minutes read.

Hibernate save() vs persist()

Session.save() The session.save() method is used to save the transient object by assigning a generated value or using a current value of the identifier property. In other words, the save() method is used...

3 minutes read.

Hibernate Merge

Hibernate Merge Merge is a method available in Hibernate which is used to update the existing records. However, it creates a copy from the passed entity objects and returns it. In other words, the merge()...

2 minutes read.

Hibernate vs. JDBC

What is Hibernate? Hibernate is an Object-Relational Mapping (ORM) tool which reduces the difficulty in the application development. Hibernate provides a framework that interacts with the data stored in the databases. It also uses...

2 minutes read.

Hibernate vs. JPA

What is JPA? JPA stands for Java Persistence API, which defines a set of functionalities, standards, and concepts to the ORM tool. It is a framework used to manage relational databases. It is available...

2 minutes read.

Architecture of Hibernate

Next → Hibernate is an ORM framework with a layered architecture. It consists of many objects, such as a persistent object, sessionfactory object, transaction object, session, etc.  There are mainly three layers in Hibernate...

2 minutes read.