Hibernate Inheritance - Single Table

Hibernate Inheritance

In this inheritance strategy, only one table is created for all the classes involved in the hierarchy with an additional column known as a discriminator column. The discriminator column helps indifferentiating between the two subclasses. A SINGLE_TABLE strategy is the default strategy.

Following are the annotations used in this strategy:

  1. @Inheritance- It defines the inheritance strategy used in the application. This annotation is specified on the entity class that is the root of all the entity classes.
  • @DiscriminatorColumn- It specifies the discriminator column for SINGLE_TABLE and JOINED inheritance strategies.
  • @DiscriminatorValue- Discriminator values are the values of the @DiscriminatorColumn. This annotation is used to specify the values of the discriminator column for the given type entity.

Syntax of SINGLE_TABLE Inheritance

@Inheritance(strategy=InheritanceType.SINGLE_TABLE)

If @Inheritance annotation is not specified or no strategy is specified, it will consider SINGLE_TABLE strategy by default.

Example of SINGLE_TABLE Inheritance

In this example, we are taking three classes; i.e., Payment.java, Card.java, and Cheque.java.

The class- hierarchy is given below:-

Example of SINGLE_TABLE Inheritance
  1. Create all POJO classes.

In this step, we are going to create all the persistent classes, i.e., Payment.java, Card.java, and Cheque.java.

Payment.java

import javax.persistence.Column;
 import javax.persistence.DiscriminatorColumn;
 import javax.persistence.DiscriminatorType;
 import javax.persistence.Entity;
 import javax.persistence.Id;
 import javax.persistence.Inheritance;
 import javax.persistence.InheritanceType;
 import javax.persistence.Table;
 @Entity
 @Table(name="payment")
 @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
 @DiscriminatorColumn(name = "paymtmode", discriminatorType =
 DiscriminatorType.STRING, length = 10)
 public class Payment {
  @Id
  @Column(name="payid")
  private int id;
  @Column(name="amount")
  private int amount;
  public int getId() {
  return id;
  }
  public void setId(int id) {
  this.id = id;
  }
  public int getAmount() {
  return amount;
  }
  public void setAmount(int amount) {
  this.amount = amount;
  }
 } 

  Card.java

import javax.persistence.Column;
 import javax.persistence.DiscriminatorValue;
 import javax.persistence.Entity;
 @Entity
 @DiscriminatorValue(value="card")
 public class Card extends Payment{
  @Column(name="cardnum")
  private int cardno;
  @Column(name="crdtype")
  private String card_type;
  public int getCardno() {
  return cardno;
  }
  public void setCardno(int cardno) {
  this.cardno = cardno;
  }
  public String getCard_type() {
  return card_type;
  }
  public void setCard_type(String card_type) {
  this.card_type = card_type;
  }
  } 

 Cheque.java

import javax.persistence.Column;
 import javax.persistence.DiscriminatorValue;
 import javax.persistence.Entity;
 @Entity
 @DiscriminatorValue(value="cheque")
 public class Cheque extends Payment {
  @Column(name="chqnum")
  private int chequeno;
  @Column(name="chqtype")
  private String cheque_type;
  public int getChequeno() {
  return chequeno;
  }
  public void setChequeno(int chequeno) {
  this.chequeno = chequeno;
  }
  public String getCheque_type() {
  return cheque_type;
  }
  public void setCheque_type(String cheque_type) {
  this.cheque_type = cheque_type;
  } 
 } 
  • Create the Configuration file.

The configuration file contains the information of mapping classes and database. We will map all the persistent classes in the configuration file (hibernate.cfg.xml).

hibernate.cfg.xml





org.hibernate.dialect
.MySQL5Dialect

com.mysql.jdbc.Driver
jdbc:mysql://
localhost:3306/example
root
root
update    
    





 
  • Create the main class that stores the object of Persistent object

In this step, we are going to create a main class (which contains the main method) that stores the object of the persistent class.

App.java

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
  
public class App 
{
public static void main( String[] args )
{
Configuration cfg= new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory s= cfg.buildSessionFactory();
Session session=s.openSession();
session.beginTransaction();
                        
Pay p=new Pay();
p.setAmount(5100);
                                
Card c= new Card();
c.setAmount(1000);
c.setCardno(33558882);
c.setCard_type("VISA");
                                
Cheque chq=new Cheque();
chq.setAmount(11100);
chq.setChequeno(010036);
chq.setCheque_type("ORDER");
                                 
session.save(p);
session.save(c);
session.save(chq);
                                
                                 
session.getTransaction().commit();
                                 
System.out.println( "successfully added" );
}  
} 
  • OUTPUT
Hibernate Inheritance - SINGLE TABLE
  •  DATABASE TABLE
DATABASE TABLE Hibernate Inheritance

DISADVANTAGES

The main disadvantages of this strategy are:

  • Most of the values are null in the table; hence, we cannot apply not null constraint.
  • In this strategy, the table cannot be normalized, which means we cannot expand this table into new tables or columns.

To overcome these disadvantages, we use TABLE_PER_CLASS strategy.


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

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 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 Inheritance - Single Table

Hibernate Inheritance In this inheritance strategy, only one table is created for all the classes involved in the hierarchy with an additional column known as a discriminator column. The discriminator column helps indifferentiating between...

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

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

Lazy Loading in Hibernate

Lazy loading is a fetching technique used for all the entities in Hibernate. It decides whether to load a child class object while loading the parent class object. When we use association mapping...

3 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 Named Query Using XML

A named query is a technique used to assemble all the queries (Native SQL and HQL) in a specific location and refer them by some name. It helps in reducing the mess...

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 SessionFactory

Next → Hibernate SessionFactory A SessionFactory is an interface in Hibernate that create the instances of Session interface. It is a heavy weight object, and it is usually created during the application...

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.