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 the specifications of the Java Persistence API (JPA).

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

  • @Entity- It is used for making a bean class as an entity bean, so it must contain a no-arg constructor.
  • @Table- It is used to create a table for the annotated entity.
  • @Id- The primary key in the table is denoted as @Id.
  • @Generatedvalue- It is used to auto-generate the value of the @Id field.
  • @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:

<dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-core</artifactId>
     <version>5.3.1.Final</version> 
 </dependency>
 <dependency>
     <groupId>org.hibernate</groupId> 
     <artifactId>hibernate-validator</artifactId>
     <version>6.0.17.Final</version>
 </dependency> 

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

Let’s create a configuration file that contains information about the mapping file and a relational database.

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE hibernate-configuration PUBLIC  
         "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
         "http://www.hibernate.org/dtd/hibernate-configuration-5.3.dtd">  
 <hibernate-configuration>  
     <session-factory>  
     <property name="hibernate.hbm2ddl.auto">update</property>    
         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    
         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> 
         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>   
         <property name="connection.username">root</property>                        //write your username
         <property name="connection.password">root</property>                       //write your password
         <mapping class="com.hibernate.pack.Book"/>  
     </session-factory>  
 </hibernate-configuration>  

4. Create the Application Class

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

    Let’s create AppTest.java.

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

OUTPUT

Annotation Example in Hibernate

Table- book01

Hibernate annonation

Related Topics

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.

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 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 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 GeneratedValue Strategies

Hibernate GeneratedValue Strategies Hibernate supports some generation strategies to generate a primary key in the database table. We can access the strategy with the help of @GeneratedValue annotation. @GeneratedValue The @GeneratedValue annotation specifies how to...

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.

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 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 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 Inheritance Table Per Class

In this inheritance strategy, table per class is generated. It means a separate table is generated for each POJO class involved in the hierarchy. Unlike the SINGLE_TABLE strategy, there are no nullable values...

3 minutes read.

Hibernate Web Application with Example

Let us create a hibernate web Application. Here we need JSP file for presentation. There are steps given below for the web app creation. index.jsp This page will show a registration form. It takes 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 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-One Mapping

Many-to-One Hibernate Mapping with Example A Many-to-One association mapping is the reverse of One-to-Many association mapping. For example, many (customers) are associated with one (vendor). In Hibernate, Many-to-One association mapping is applied from child class...

3 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 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 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 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 Web Application Example

Web Application Example with Hibernate In this section, we create a hibernate web Application. Here we are using a JSP file for presentation. Example of creating a web application using hibernate index.jsp This page will show a...

2 minutes read.