Newsletter

Hibernate Inheritance: Table Per Concrete Class Hierarchy

Hibernate » on Jun 21, 2011 { 44 Comments } By Sivateja

Something like previous example but the changes are at mapping file only, and one more thing is..

x number of derived classes = x number of tables in the database

  • Once we save the derived class object, then derived class data and base class data will be saved in the derived class related table in the database
  • for this type we need the tables for derived classes, but not for the base class
  • in the mapping file we need to use one new element <union-subclass — >under <class —>

Required files_

  • Payment.java (Base class)
  • CreditCard.java (Derived class)
  • Cheque.java (Derived class)
  • ClientForSave.java (for our logic)
  • Payment.hbm.xml
  • hibernate.cfg.xml

 

Payment.java:

package str;

public class Payment{

	private int paymentId;
	private double amount;

	public int getPaymentId() {
		return paymentId;
	}
	public void setPaymentId(int paymentId) {
		this.paymentId = paymentId;
	}
	public double getAmount() {
		return amount;
	}
	public void setAmount(double amount) {
		this.amount = amount;
	}	 

}

CreditCard.java:

package str;

public class CreditCard extends Payment{

	private String CreditCardType;

	public String getCreditCardType() {
		return CreditCardType;
	}

	public void setCreditCardType(String creditCardType) {
		CreditCardType = creditCardType;
	}

}

Cheque.java:

package str;

public class Cheque extends Payment{

	private String ChequeType;

	public String getChequeType() {
		return ChequeType;
	}

	public void setChequeType(String chequeType) {
		ChequeType = chequeType;
	}

}

ClientForSave.java

package str;

import org.hibernate.*;
import org.hibernate.cfg.*;
 
public class ClientForSave { 
 
    public static void main(String[] args)
    {
 
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml"); 
 
        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();

        CreditCard c=new CreditCard();
 
        c.setPaymentId(10);
        c.setAmount(2500);
        c.setCreditCardType("Visa");

 
        
        Cheque c1=new Cheque();
        
        c1.setPaymentId(11);
        c1.setAmount(2600);
        c1.setChequeType("ICICI");

        
        
        Transaction tx = session.beginTransaction();
        session.save(c);
        session.save(c1);
        System.out.println("Object saved successfully.....!!");
        tx.commit();
        session.close();
        factory.close();
    }
 
}

Payment.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="str.Payment" table="PAYMENT">

<id name="paymentId" column="pid" />
<property name="amount" column="amt" />

<union-subclass name="str.CreditCard">
<property name="CreditCardType" column="cctype" length="10" />
</union-subclass>

<union-subclass name="str.Cheque">
<property name="ChequeType" column="cqtype" length="10" />
</union-subclass>

</class>
</hibernate-mapping>

 

hibernate.cfg.xml:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>

<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>

<mapping resource="Payment.hbm.xml" />

</session-factory>
</hibernate-configuration>

Eclipse Output

In the database

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

44 Responses to “Hibernate Inheritance: Table Per Concrete Class Hierarchy”
  1. Yogesh says:

    Nice explaination java4s, thanks.

  2. Java4s says:

    @Yogesh

    Thanks for your feedback 🙂

  3. Anupam says:

    Nicely distinguished between the three types of Hibernate Inheritance!

  4. Suresh says:

    This is nice explanation. But there is something shaking my mind.
    Since data is getting stored only in 2 tables i.e. Cheque and CreditCard; do we still need to have “Payment” table?
    I mean, why is there a table which is not getting used? Can we have some kind of implementation approach which will eliminate need of this table and still achieving this hierarchy?

    Thanks in advance for your reply.

    • Abhishek Zade says:

      That is the limitation of Table per Concrete Class .
      To avoid this ,need to keep super class as Abstract which will be extends by sub class..

  5. suresh says:

    Really good explanation.

  6. Java4s says:

    @suresh

    I am showing all the tables, just for your understanding purpose 🙂

  7. krishna says:

    Hi SivaTej,

    I read some articles on mappings but finally i got clear picture while i am reading your blog.

    Thanks alot. Keep up your good work.

    KRISHNA

  8. Anasuya says:

    Hi Java4s thank you very much for the nice explanation,but can you please explain as when to use which hierarchy in real time?
    Thanks in advance…

  9. naveen says:

    good work….it is working…i did ur inheritence hierarchy programs…i understood…thank u very much….

  10. swapna says:

    Neat and clear explaination

  11. Hi Java4s u r doing a grt job 🙂

    but i also want to know what @Anasuya says

    when to use which Inheritance hierarchy in real time?

    Can u explain this ?

    Advance thanks

  12. Kiran N says:

    Hi Java4s Team,

    Its really nice explanation , thanks a lot Java4s team keep it up..

  13. Hi,
    I want to ask that in this example there is no table name provided for sub classes like CreditCard and Cheque, insted Payment Class is mapped with PAYMENT table that is of no use ? can some body explain me ?

  14. sarthi says:

    This is nice explanation. But there is something shaking my mind.
    Since data is getting stored only in 2 tables i.e. Cheque and CreditCard; do we still need to have “Payment” table?
    I mean, why is there a table which is not getting used? Can we have some kind of implementation approach which will eliminate need of this table and still achieving this hierarchy?

  15. could you tell me the real time scenarious for all the types of inheritance mappings..?

  16. murali says:

    Thank you so much…..

  17. Raj says:

    I gone through your most of blogs from this site… the way you have written this blog is awesome. By Reading itself anyone can understand the concept. Thank you very much!!

  18. karthick says:

    why did you left the sub class table name in the …you have mentioned the base class table only…confused….please clear the doubt..ASAP …thanx in advance

  19. Prasad says:

    @karthick

    we do not left the sub classes with table names….otherwise error will rise…
    Here sir has taken same name for both table name and class name. In this situation it is optional to mention table name…

  20. Yogendra Joshi says:

    Nice explanation, short and simple. Easy to understand with these examples.

  21. P.Pradeep says:

    Thank you for your explanation Sivateja Kandula.

  22. Pranab Pradhan says:

    Detailed explanation, well done java4s!!! Keep up good work!!!

  23. raghava says:

    siva teja, u said only tables for derived classes but here we end up totally unused base class? didnt understand? why 3 tables?

  24. pavan says:

    Siva…. U said as per TablePerConcrete class require derived table to store all derived as well as base class, but in the mapping file, u mentioned table name for the base table PAYMENTS. Am i correct?

  25. G j says:

    for this type we need the tables for derived classes, but not for the base class ….I am not agree to you ….if tere will b no table for base class then if i only wants to save the data of a base class object where it will get saved ….

  26. krishna says:

    Excellent….

  27. Pranab says:

    Nice explanation. Thanks

  28. saroj kumar says:

    SIR is is it possible than Add next and prev.. butn on top also ..bcz if i wan to moove the next chapter thn we need to scroll every time

  29. Mohan Rao says:

    Hi JAVA4S Team,
    Thanks for sharing these details , it is helping us to explore more on hibernate.

    KINDLY CHECK THE EXPLANATIONS OF TPC (Table per Concrete class) and TPS (Table per Concrete class), please recheck it once.

    Regards
    Mohan

  30. Santhosh P says:

    Thanks for nice tutorial. I am just little bit confusing.

    In Table Per Concrete Class,

    x number of derived classes = x number of tables in the database or

    x number of classes = x number of tables in the database

    it is contracting with table per subclass. could you please explain

  31. vijay krishna says:

    In the mapping file subclass table name mapping is missing

  32. Pravin Dhas says:

    Very nice explanation for all the topics. Thank you very much java4s.

  33. Venkat says:

    Hi Java4s,

    I want to know usage of Main class Table(Payment) in Table Per Concrete Class Hierarchy.Because we are not saving any data.

  34. Arun says:

    Hi Java4s,

    Please verify Payment.hbm.xml file on that 13th and 17th line, actually you mention
    x no'of derived tables =x no'of tables but you are not creating table in <union-subclass > tag .

    if there is any modification please rectify that it is helpful for new learners.

    Thanks for your effort sir, your way of explanation is so nice ,

  35. sundar says:

    Hi java4s, can maintain the disadvantages of each hierarchy, and easily identify the what is the purpose of perticular hierarchy

  36. Bansal Khan says:

    Do we need discriminator in case when only one class is extending the parent pojo…..???????

  37. mohammad says:

    Greate Explanation

  38. chandu says:

    Nice Explanation, Thanks

  39. Divya says:

    Hi

    Nice Explanation. Could you please clarify why the table name mapping is not provided in the below lines of Code.How the hibernate know this particular derived class is mapped to which table. Is it not required ? Do we need to specify the Main table mapping in class tag if data is not save in base table?

    <union-subclass name="str.CreditCard">
    <property name="CreditCardType" column="cctype" length="10" />
    </union-subclass>

    <union-subclass name="str.Cheque">
    <property name="ChequeType" column="cqtype" length="10" />
    </union-subclass>

  40. pankaj kumar says:

    Hi Author,
    I have some doubt in the table per concrete class.
    when queries are executing then a blank table of the parent is also creating why is that so?
    What is the use of this table?

  41. Raju Tanchak says:

    You didn't specified derived class table names, how come data got saved on corresponding table?

  42. KRISHNA MOHAN . says:

    This is nice explanation.

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.