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 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 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 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 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 Session Interface

Hibernate Session Interface A Session is an interface between the Java application and the Hibernate. It is available in the org.hibernate.session package. It should not be kept open for a long time, as it...

4 minutes read.

Hibernate merge() vs. update()

In Hibernate, both update() and merge() methods are used to convert the detached state object into the persistent state. session.merge() The merge() method is used when we want to change a detached entity into...

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

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.

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 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 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 first Example

Now we are going to create the first example in Hibernate. We will proceed step by step to develop the first Java application in Hibernate. The steps are listed below:- Create the POJO...

2 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 Configuration Properties

Hibernate Configuration Hibernate Configuration is a Java class, which allows a Java application to specify configuration parameters used in the application. As Hibernate is designed to serve in different environments, it needs a broad...

6 minutes read.