Hibernate

Hibernate Table per Class strategy Annotations Example

In this tutorials, we are going to implement Hibernate Table per Class strategy using annotations. In the previous example, we implemented the same Table per Class strategy using xml configuration.

It is recommended to see the types of inheritance strategies in hibernate for bettor understanding.

Hibernate Table per Class Annotations Example :

We can use the Hibernate Table per Class strategy, if we want to store the data of all classes hierarchy into a single database table. For this strategy we can store all classes data in a single table.

Database Table :

[sql]

CREATE TABLE payment (
     paymode varchar(6) NOT NULL,
     payid int(11) NOT NULL,
     amount double DEFAULT NULL,
     chqnumber int(11) DEFAULT NULL,
     chtype varchar(10) DEFAULT NULL,
     ccnumber int(11) DEFAULT NULL,
     cctype varchar(10) DEFAULT NULL,
     PRIMARY KEY (payid)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
[/sql]

Project Structure :

Hibernate Table per class Annotaions

Required Dependencies:

[xml]
<dependencies>
        <!– Hibernate –>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.0.Final</version>
        </dependency>
        <!– MySQL Driver –>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.0.5</version>
        </dependency>
    </dependencies>

[/xml]

Hibernate Pojo Classes :

Payment.java

[java]

package com.onlinetutorialspoint.hibernate.pojo;

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 = "paymode", discriminatorType = DiscriminatorType.STRING, length = 6)
public class Payment {
    @Id
    @Column(name = "payid")
    private Integer paymentId;
    @Column(name = "amount")
    private Double amount;

    public Double getAmount() {
        return amount;
    }

    public void setAmount(Double amount) {
        this.amount = amount;
    }

    public Integer getPaymentId() {
        return paymentId;
    }

    public void setPaymentId(Integer paymentId) {
        this.paymentId = paymentId;
    }

}
[/java]

 

In Table per class inheritance strategy, all child classes data will be stored in a single table (parent table). In our example, cardpayment and cheque payment data will be stored in payment table.

@Inheritance annotation represents, which type of strategy we are going to use. For our example it is  InheritanceType.SINGLE_TABLE.

@DiscriminatorColumn annotation is a equivalent for <discriminator> tag in xml configuration.

ChequePayment.java

[java]

package com.onlinetutorialspoint.hibernate.pojo;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

@Entity
@DiscriminatorValue(value="CHQ")
public class ChequePayment extends Payment {

    @Column(name="chqnumber")
    private int chequeNumber;
    
    @Column(name="chtype",length=10)
    private String chequeType;

    public String getChequeType() {
        return chequeType;
    }

    public void setChequeType(String chequeType) {
        this.chequeType = chequeType;
    }

    public int getChequeNumber() {
        return chequeNumber;
    }

    public void setChequeNumber(int chequeNumber) {
        this.chequeNumber = chequeNumber;
    }
    
}

[/java]

CreditCardPayment.java

[java]

package com.onlinetutorialspoint.hibernate.pojo;

import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

@Entity
@DiscriminatorValue(value="CCARD")
public class CreditCardPayment  extends Payment{
    
    @Column(name="ccnumber")
    private int cardNumer;
    
    @Column(name="cctype",length=10)
    private String cardType;

    public String getCardType() {
        return cardType;
    }

    public void setCardType(String cardType) {
        this.cardType = cardType;
    }

    public int getCardNumer() {
        return cardNumer;
    }

    public void setCardNumer(int cardNumer) {
        this.cardNumer = cardNumer;
    }
}

[/java]

HibernateUtil.java

[java]

package com.onlinetutorialspoint.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private HibernateUtil() {

    }

    private static SessionFactory sessionFactory;

    public static synchronized SessionFactory getInstnce() {

        if (sessionFactory == null) {
            Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties());
            sessionFactory = configuration.buildSessionFactory(builder.build());
        }
        return sessionFactory;

    }
}

[/java]

Completed ! Run the application.

Min.java

[java]

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.onlinetutorialspoint.hibernate.pojo.ChequePayment;
import com.onlinetutorialspoint.hibernate.pojo.CreditCardPayment;
import com.onlinetutorialspoint.util.HibernateUtil;

public class Main {

    public static void main(String[] args) {

        SessionFactory sessionFactory = HibernateUtil.getInstnce();
        Session session = sessionFactory.openSession();
        
        CreditCardPayment creditCardPayment=new CreditCardPayment();
        creditCardPayment.setPaymentId(1001);
        creditCardPayment.setAmount(30000.00);
        creditCardPayment.setCardType("ICICI");
        creditCardPayment.setCardNumer(526253252);
        
        ChequePayment chequePayment=new ChequePayment();
        chequePayment.setAmount(2000.00);
        chequePayment.setPaymentId(1002);
        chequePayment.setChequeType("ORDER");
        chequePayment.setChequeNumber(0005265232);
        
        Transaction transaction=session.beginTransaction();
        session.save(creditCardPayment);
        session.save(chequePayment);
        transaction.commit();
        session.close();
        sessionFactory.close();
        
    }
}
[/java]

 

Output :

Hibernate: insert into payment (amount, ccnumber, cctype, paymode, payid) values (?, ?, ?, 'CCARD', ?)
Hibernate: insert into payment (amount, chqnumber, chtype, paymode, payid) values (?, ?, ?, 'CHQ', ?)

Database Output :

Table Per Class Annotations output

Happy Learning :)

Download Example

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Ask a question or leave a comment