Nearby lessons

19 of 19

Hibernate - Inheritance Mapping (Table Per Subclass)

📌 What You Will Learn
  • Understand Hibernate - Inheritance Mapping (Table Per Subclass)
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Hibernate - Inheritance Mapping (Table Per Subclass) step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Inheritance Mapping (Table Per Subclass) — Account.java

  • sa.setSbranch("CS");
  • sa.setSmarks(77);
  • EmployeeAccount ea = new EmployeeAccount();
  • ea.setAccNo("a2");
  • ea.setAccName("BBB");
  • ea.setAccType("Savings");
  • ea.setEid("E1");
  • ea.setEsal(5000);
  • ea.setEaddr("Hyd");
  • Transaction tx = session.beginTransaction();
  • session.save(sa);
  • session.save(ea);
  • tx.commit();
  • System.out.println("Student Account Inserted Successfully");
  • System.out.println("Employee Account Inserted Successfully");

EXAMPLE:

Example01
Loading editor…

Inheritance Mapping (Table Per Subclass) — StudentAccount.java

Example02
Loading editor…

Inheritance Mapping (Table Per Subclass) — EmployeeAccount.java

Example03
Loading editor…

Inheritance Mapping (Table Per Subclass) — Account.hbm.xml

Example04
Loading editor…

Inheritance Mapping (Table Per Subclass) — hibernate.cfg.xml

Example05
Loading editor…

Inheritance Mapping (Table Per Subclass) — Test.java

Example06
Loading editor…

Inheritance Mapping (Table Per Subclass) — Account.java

To represent Table Per Class Inheritance Mapping javax.persistence package has provided the following three Annotations.

1) @Inheritance 2) @DiscriminatorColumn 3) @DiscriminatorValue

1) @Inheritance

 This annotation is able to specify Inheritance Mapping strategy. @Inheritance(strategy=value) Where value may be SINGLE_TABLE constant from InheritanceType enum.

EX: @INheritance(strategy=InheritanceType.SINGLE_TABLE)

2) @DiscriminatorColumn  This annotation is able to represent Discriminator Column. @DiscriminatorColumn(name ="--") Where "name" is able to take discriminator column name.

EX: @DiscriminatorColumn(name="TYPE")

Note: The above two annotations must be used at super class. 3) @DiscriminatorValue

 It able to provide value to the discriminator column, it must be specified at sub class

Example:

Example07
Loading editor…

Inheritance Mapping (Table Per Subclass) — StudentAccount.java

Example08
Loading editor…

Inheritance Mapping (Table Per Subclass) — EmployeeAccount.java

Example09
Loading editor…

Inheritance Mapping (Table Per Subclass) — hibernate.cfg.xml

Example10
Loading editor…

Inheritance Mapping (Table Per Subclass) — Test.java

Example11
Loading editor…

Table Per Sub class — Payment.java

 In case of "Table Per Subclass" inheritance mapping, we have to prepare a seperate table for each and every class[for both super class and sub classses] existed in inheritance.

 While preparing tables for sub classes we have to provide a join column which must be primary key in super class respective table and in sub class respectiove tables.

 In hibernate applications, if we store sub class objects in database then Hibernate software has to recognize and store super class properties data in super class respective table and sub class respective data in sub class respectgive tables.  To achieve this requirement, Hibernate software has to recognize super class properties

and sub class properties seperately, for this we have to provide sub classes configuration seperatly in hibernate mapping file.  To provide "Table Per Subclass" inheritance mapping we have to use the following xml tags in mapping file.

  • <hibernate-mapping>
  • <class name="--" table="--"
  • <joined-subclass name="--" table="--">
  • <key column="--"/>
  • </join-subclass>
  • </class>
  • </hibernate-mapping>

 Where "<joined-subclass>" tag is able to configure sub class, where "name" attribute will take fully qualified name of the respective sub class and "table" attribute will take sub class respective table name.

 Where "<key>" tag is able to take join key which is available in sub class respective table.

Example:

Example12
Loading editor…

Table Per Sub class — CardPayment.java

Example13
Loading editor…

Table Per Sub class — ChequePayment.java

Example14
Loading editor…

Table Per Sub class — payment.hbm.xml

Example15
Loading editor…

Table Per Sub class — hibernate.cfg.xml

Example16
Loading editor…

Table Per Sub class — Test.java

Example17
Loading editor…

Table Per Sub class — Payment.java

Note: The above application required the followeing database

SQL> desc payment;

Name Null? Type

TX_ID NOT NULL VARCHAR2(5)

PAY_DATE VARCHAR2(10)

PAY_AMT

SQL> desc card_payment;

Name Null? Type

TX_ID NOT NULL VARCHAR2(5)

CARD_NO NUMBER(8)

EXPR_DATE VARCHAR2(10)

SQL> desc cheque_payment;

Name Null? Type

TX_ID NOT NULL VARCHAR2(5)

CHEQUE_NO NUMBER(8)

ACC_NO VARCHAR2(10)

SQL>

To represent "Table Per Subclass" inheritance mapping mechanism, javax.persistence package has provided the following Annotations

1) @Inheritance 2) @PrimaryKeyJoinColumn

1) @Inheritance

 This annotation is able to represent a particular Inheritance mapping mechanism,it will use "strategy" member to take a particular inheritance mapping, where "strategy" attribvute will take "JOINED" value constant from "InheritanceType" enum.

EX: @Inheritance(strategy=IOnheritanceType.JOINED) 2) @PrimaryKeyJoinColumn

 This annotation will be used at sub classes inorder to provide Join Key column name. It will use "name" attribute to provide "join key column".

EX: @PrimaryKeyJoinColumn(name="TX_ID")

Example:

Example18
Loading editor…

Table Per Sub class — CardPayment.java

Example19
Loading editor…

Table Per Sub class — ChequePayment.java

Example20
Loading editor…

Table Per Sub class — hibernate.cfg.xml

Example21
Loading editor…

Table Per Sub class — Test.java

Example22
Loading editor…

Table Per Concreate Class — Person.java

In "Table per Concreate Class" inheritance mapping , we will prepare a seperate table for each and every sub class containing the columns representing both the super class properties and the respective sub class properties.

In the above context, if we save any sub class object then Hibernate software has to distribute sub class objects data in the respective table and in the respective columns. To achieve this we have to use the following xml tags in hibernate mapping file.

  • <hibernate-mapping>
  • <class name="--">
  • <union-subclass name="--" table="--">
  • <property name="--" column="--"/>
  • </union-subclass>
  • </class>
  • </hibernate-mapping>

Where "<union-subclass> tag is able to provide mapping between a particular sub class and the respective table, where "name" attribute will take sub class name and table attribute will take the respective table name.

Example:

Example23
Loading editor…

Table Per Concreate Class — Employee.java

Example24
Loading editor…

Table Per Concreate Class — Customer.java

Example25
Loading editor…

Table Per Concreate Class — Person.hbm.xml

Example26
Loading editor…

Table Per Concreate Class — hibernate.cfg.xml

Example27
Loading editor…

Table Per Concreate Class — Test.java

Example28
Loading editor…

Database — Person.java

SQL> create table employee (PNAME varchar2(10) primary key, PADDR varchar2(10), EID varchar2(5), ESAL float); SQL> commit; SQL> create table customer(PNAME varchar2(10) primary key, PADDR varchar2(10), CID varchar2(5), CMOBILE varchar2(20)); SQL> commit;

To represent this inheritance mapping mechanism we have to use @Inheritance() annotation , where we have to use "TABLE_PER_CLASS" constant from INheritanceType enum as value to 'strategy' member.

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)

Example:

Example29
Loading editor…

Database — Employee.java

Example30
Loading editor…

Database — Customer.java

Example31
Loading editor…

Database — hibernate.cfg.xml

Example32
Loading editor…

Database — Test.java

Example33
Loading editor…

Association Mapping

In General, in Enterprise applications we will use both Object Oriented Data Model and Relational Data Model to represent data. In Enterprise applications we will use Object Oriented Data Model in Front-End applications toreprepsent data and we will used Relational data Model in Back-End Applications to represent Data.

In the above context, both the data models are having their own approaches to represent data, the differences between data models may provide mismatches between data models, it may reduce data persistency in Enterprise Applications.

In the above context, to improve data persistency we must use ORM implementations, Hibernate is an ORM implementation , it able to provide solutions for mismatchs between Data models. In Enterprise applications, we are able to get Associations mismatch while achieving associations in Object Oriented Data Model and in Relational Data Model.

IN Enterprise Applications, the main intention of Associations is to to improve data navigation between entities and to improve communication between entities.

In Object Oriented Data Model, we are able to achieve associations by declaring one or Collection of reference variables of an entity class in another entity class.

Example34
Loading editor…

Association Mapping

In relational Data Model, we are able to achieve associations in the following three ways.

1) By defining Primary Key-Foreign Key relations between tables 2) By Providing Join column between tables 3) By Defining Join table between tables.

To resolve the above associations mismatch between both the data models Hibernate has provided "Association Mappings".

Hibernate has provided the following four types of Associations mappings inorder to resolve Associations mismatch.

  • One-To-One Association Mapping
  • One-To-Many Association Mapping
  • Many-To-One Association Mapping
  • Many-To-Many Association Mapping

One-To-One Association Mapping — Employee.java

It is a relation between entities, where one instance of an entity should be mapped with exactly one instance of another entity. EX: Every Employee must have exactly one individual Account.

In Hibernate applications, to achieve One-To-One Associations, we have to use the following tag in mapping file.

<one-to-one name="--" class="--" cascade="--"/>

 Where "name" attribute take property name of the entity class.  Where "class" attribute will take Fully qualified name of the associated class.  Where "cascade" attribute will take the values like all, none, insert, update and delete

inorder to perform operations in cascading style, that is, if we delete employee table automatically Account table must also be deleted.

Example:

Example36
Loading editor…

One-To-One Association Mapping — Account.java

Example37
Loading editor…

One-To-One Association Mapping — Employee.hbm.xml

Example38
Loading editor…

One-To-One Association Mapping — Account.hbm.xml

Example39
Loading editor…

One-To-One Association Mapping — hibernate.cfg.xml

Example40
Loading editor…

One-To-One Association Mapping — Test.java

Example41
Loading editor…

One-To-One Association Mapping — Employee.java

In Hibernate Applications , to represent one-to-one association JPA has provided the following annotation as part of javax.persistence package.

@OneToOne(cascade=Val) Where val may be the constants like ALL, DETACH, MERGE, REFREESH, REMOVE, PERSIST from CascadeType enum.

The above annotation must be provided just before the entity reference variable in container entity or just above of the getXXX() method w.r.t the entity reference variable.

EX:

Example42
Loading editor…

One-To-One Association Mapping — Account.java

Example43
Loading editor…

One-To-One Association Mapping — hibernate.cfg.xml

Example44
Loading editor…

One-To-One Association Mapping — Test.java

Example45
Loading editor…

One-To-Many Association — Employee.java

It is a relation between entities where one instance of an entity should be mapped with multiple instances of another entity.

EX: Single Department has Multiple Employees

In Hibernate applications, to represent One-To-Many association we have to use the following tags in mapping files.

  • <hibernate-mapping>
  • <class name="--" table="--">
  • <set name="---" cascade="--">
  • <key column="---"/>
  • <one-to-many class="---"/>
  • </set>
  • </class>
  • </hibernate-mapping>

 Where <set> tag is able to represent Collection object, that is, many side in one-to-many and in many-to-many.

 Where "name" attribute is representing property name which is representing Collection.  Where "cascade" attribute will take cascade values like all, insert,....  Where <key> tag can be used to specify Join key configuration.  Where "column" attribute in <key> tag is able to join column name.  Where "<one-to-many>" tag is able to represent one-To-many association.  Where "class" attribute in <one-to-many> tag will take class name that is contained class.

Example:

Example46
Loading editor…

One-To-Many Association — Department.java

Example47
Loading editor…

One-To-Many Association — Employee.hbm.xml

Example48
Loading editor…

One-To-Many Association — Department.hbm.xml

Example49
Loading editor…

One-To-Many Association — hibernate.cfg.xml

Example50
Loading editor…

One-To-Many Association — Test.java

Example51
Loading editor…

One-To-Many Association — Employee.java

In Hibernate Applications, to represent One-To-Many association , JPA has provided the following annotation.

@OneToMany(cascade=CascadeType.ALL)

EX:

Example52
Loading editor…

One-To-Many Association — Department.java

Example53
Loading editor…

One-To-Many Association — hibernate.cfg.xml

Example54
Loading editor…

One-To-Many Association — Test.java

Example55
Loading editor…

Many-To-One Association

It is a relation between entity classes, where multiple instances of an entity should be mapped with exactly single instance of another entity.

EX: Multiple Students have joined with single branch — Branch.java

To provide Many-To-One Association in Hibernate applications then we have to use the following tag in mapping file.

<many-to-one name="--" class="--" cascade="all"/>

 where "name" attribute will take property name which is representing many to one relation.  where "class" attribute will take contained class name.  where "cascade" attribute will take the values like all, insert,.......

EX:

Example57
Loading editor…

EX: Multiple Students have joined with single branch — Student.java

Example58
Loading editor…

EX: Multiple Students have joined with single branch — Branch.hbm.xml

Example59
Loading editor…

EX: Multiple Students have joined with single branch — Student.hbm.xml

Example60
Loading editor…

EX: Multiple Students have joined with single branch — Test.java

Example61
Loading editor…

EX: Multiple Students have joined with single branch — Branch.java

To represent many-to-one association, JPA has provided a seperate annotation like @ManyToOne(calcade=CascadeType.ALL)

Example:

Example62
Loading editor…

EX: Multiple Students have joined with single branch — Student.java

Example63
Loading editor…

EX: Multiple Students have joined with single branch — hibernate.cfg.xml

Example64
Loading editor…

EX: Multiple Students have joined with single branch — Test.java

Example65
Loading editor…

Many-To-Many Associations — Course.java

It is a relation between entities , where multiple instances of an entity must be mapped with multiple instances of another entity. EX: Multiple Students have joined with Multiple Courses.

To repesent Many-To-Many mapping we have to use the following tags in mapping file. <set name="--" table="--" cascade="--"> <key column="---"/> <many-tomany column="--" class=""/>

</set>

 Where "<set>" tag is representing many side, where "name" attribute in <set> tag will take property name which is providing many side , where "table" attribute will take join_table name, where "cascade" will take "all", "insert", "update",.....

 Where "<key>" tag is able to take primary key of the container represented table, where "column" attribute will take that value.

 Where "<many-to-many>" tag will represent many-to-many association, where "column" attribute will take target table primary kery column name, where "class" attribute will take target class name.

Example:

Example66
Loading editor…

Many-To-Many Associations — Student.java

Example67
Loading editor…

Many-To-Many Associations — Course.hbm.xml

Example68
Loading editor…

Many-To-Many Associations — Student.hbm.xml

Example69
Loading editor…

Many-To-Many Associations — hibernate.hbm.xml

Example70
Loading editor…

Many-To-Many Associations — Test.java

Example71
Loading editor…

Retrieving the data through annotation — Hibernate.cfg.xml

To represent many _to_many association mapping,EJB3 has provide the following annotations.

@ManyTomany(cascade=”_”) @jointable(name=”_”,joincolumns=”_”,inversejoincolumns=”_”) @joincolumn(name=”_”)

 Where, @Manyto many annotation will represent many_to_many association mapping.  Where,@jointable annotation will represent the meta data about the join table.

 Name->join table nam e,joincolumns->array of @joincolumn annotation;  Inversejoincolumn->array on @joincolumn annonation to represent inverse

join key configuration.

 Where, @joincolumn annotation can be used to represent a column available in join table.  Where @join column annotation must be user as nested annotation to @jointable

annotation.

Example72
Loading editor…

Retrieving the data through annotation — Student.java

Example73
Loading editor…

Retrieving the data through annotation — Course.java

Example74
Loading editor…

Retrieving the data through annotation — ClientApp.java

Example75
Loading editor…
📝 Key Takeaways
  • Key ideas of Hibernate - Inheritance Mapping (Table Per Subclass) explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.