Saturday , April 29 2017
Home / Hibernate / Hibernate Table per Class strategy Annotations Example

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. Here is the example for hibernate table per class inheritance strategy using annotations:

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 :


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

Project Structure :

Hibernate Table per class Annotaions

Required Dependencies:

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

Hibernate Pojo Classes :

Payment.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;
    }

}

In Table per class inheritance strategy, all child classes data will be stored in a single table (parent table). In our example cardpayment and chequepayment 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


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;
    } 
    
}

CreditCardPayment.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;
    }
}

Hibernate Utility Class :

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

    }
}

Completed ! Run the application.

Min.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();
        
    }
}

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

Here you can also download the complete example of hibernate table per class using annotations. If you find any problem, please let us know by leaving the comment.

Download Example

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

Hibernate Projection with Example

In this tutorials, we are going to learn about Hibernate Projection with a simple example. …

Leave a Reply

Your email address will not be published. Required fields are marked *