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

Annotation Example in Hibernate

Hibernate Annotation 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...

3 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.

Cascade in Hibernate

Cascading is a feature in Hibernate, which is used to manage the state of the mapped entity whenever the state of its relationship owner (superclass) affected. When the relationship owner (superclass) is saved/...

3 minutes read.

Hibernate Features

1. Lightweight Hibernate is a lightweight framework as it does not contains additional functionalities; it uses only those functionalities required for object-relational mapping. It is a lightweight framework because it uses persistent...

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.

Hibernate Query Language (HQL)

Hibernate provides its query language called Hibernate Query Language (HQL). HQL is an object-oriented query language, similar to the native SQL language, and it works with persistent objects. It is a database-independent and...

2 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 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 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.

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 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 Second-Level Cache

The Second-level cache is related to the SessionFactory object. Once the SessionFactory is closed, all the second-level cache data associated with it will be lost. The cache manager will also get closed. Cache provider The...

5 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.

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 Dialects

Hibernate Dialects Dialect is a Java class available in org.hibernate.dialect package, which helps to map Java Application with the database. To interact with the database, we need to define the required database dialect in...

2 minutes read.

Hibernate Many-to-Many Mapping

Many-to-Many Hibernate Mapping with Example In Many-to-Many association mapping, more than one objects of a persistent class are associated with more than one objects of another persistent class. For example, many (categories) are related to...

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