Hibernate - SPLessons

Hibernate inheritance

Home > Lesson > Chapter 18
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Hibernate inheritance

Hibernate inheritance

shape Description

Hibernate Inheritance is the one of the main concept for the re-usability purpose, The basic overview regarding hibernate inheritance is for instance two classes are there which are derived from the parent class, Where each class will have one object that needs to stored in database, If developer save derived class object in database, Then automatically parent class object will be also stored but the thing developer should specify which class object is stored in which table. When creating a POJO class in Hibernate application, if multiple POJO classes contain any common properties then for re-usability, the common properties are separated into superclasses and extended into subclasses. Following are the mapping of inheritence.

Table Per class

shape Description

In Table Per class Hierarchy, hibernate stores all instance of classes in a single table.
    1. At the time of persisting the objects into the database, Hibernate also inserts a discriminator value of an object into the database.
    2. At the time of creating a table in the database, take the one extra column called discriminator column.
    3. The column related to subclasses should not be applied with a non-null constraint.
    4. In hibernate mapping  file, subclass tag has to be configured under the class tag.
Example:
  1. Suppose take one super class and two sub classes which are Instances of all class properties stored in one table.

shape Conceptual figure

shape Examples

  • Create the project directry structure
  • Create persistence classes or POJO classes.
Payment.java [java]package com.itoolsinfo; 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; } } [/java] Here the developer created the class Payment and the class will be extended by other classes to extend the properties from this class, here the developer used set and get methods, actually the purpose of Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, one can define get methods to access these variables, and set methods to modify them. CreditCard.java [java]package com.itoolsinfo; public class CreditCard extends Payment { private int cardNumber; private String cardType; public int getCardNumber() { return cardNumber; } public void setCardNumber(int cardNumber) { this.cardNumber = cardNumber; } public String getCardType() { return cardType; } public void setCardType(String cardType) { this.cardType = cardType; } } [/java] Here created the class CreditCard that is extending Payment class to acquire the properties, here also used set and get methods for the card type. DebitCard.java [java]package com.itoolsinfo; public class DebitCard extends Payment { private int pinNumber; private String cardName; public int getPinNumber() { return pinNumber; } public void setPinNumber(int pinNumber) { this.pinNumber = pinNumber; } public String getCardName() { return cardName; } public void setCardName(String cardName) { this.cardName = cardName; } } [/java] Here the developer created the DebitCard class and it is also extending the class Payment, here also used set and get methods for getting pin number and getting card name, the functionality of set and get methods alreay disscussed in payment class.
  • Map all the POJO classes in mapping file.
payment.hbm.xml [xml]<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.itoolsinfo.Payment" table=" SalaryDetails" discriminator-value="employee"> <id name="paymentId" column="pid"> <generator class="increment"/> </id> <discriminator column="paymentmode" type="string"></discriminator> <property name="amount" column="amount"/> <subclass name="com.iquickinfo.CreditCard" discriminator-value="creditcard"> <property name="cardNumber"/> <property name="cardType" length="20"/> </subclass> <subclass name="com.iquickinfo.DebitCard" discriminator-value="debitcard"> <property name="pinNumber"/> <property name="cardName" length="20"/> </subclass> </class> </hibernate-mapping> [/xml] The generator class sub element of id utilized to produce the unique identifier for the objects of persistence class. There are numerous generator classes characterized in the Hibernate Framework. All the generator classes actualizes the org.hibernate.id.IdentifierGenerator interface.
  • Configure the mapping file in Configuration file.
hibernate.cfg.xml [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:@localhost:1521:XE</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="hibernate.hbm2ddl.auto">create</property> <property name="show_sql">true</property> <mapping resource="payment.hbm.xml"/> </session-factory> </hibernate-configuration> [/xml]
Properties Description
hibernate.connection.driver_class The JDBC driver class.
hibernate.dialect This property makes Hibernate generate the suitable SQL for the picked database.
hibernate.connection.url The JDBC URL to the database instance.
hibernate.connection.username The database username.
hibernate.connection.password The database password.
hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool.
hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection.
  • Create the SPLessons class and stores the all POJO class objects, to perform the database operations.
SPLessons.java [java]package com.itoolsinfo; import javax.security.auth.login.Configuration; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class SPLessons { public static void main(String args[]) { SessionFactory factory=new Configuration().configure().buildSessionFactory(); Session session=factory.openSession(); Payment payment=new Payment(); payment.setPaymentId(3); payment.setAmount(20000); CreditCard creditcard=new CreditCard(); creditcard.setCardNumber(5678); creditcard.setCardType("visa"); DebitCard debitcard=new DebitCard(); debitcard.setPinNumber(6785); debitcard.setCardName("KARUR VYSYA BANK"); Transaction transaction=session.beginTransaction(); session.save(payment); session.save(creditcard); session.save(debitcard); transaction.commit(); session.close(); System.out.println("Payment datails all are entered using annotations"); } } [/java] SessionFactory is an interface, which is available in “org.hibernate” package. Session factory is long live multithreaded object. Usually one session factory should be created for one database. When you have multiple databases in your application you should create multiple SessionFactory object. Output table appears in database table. This can be done using following sql command. select * from SalaryDetails;
In Hibernate, Table Per Class Hierarchy uses Annotations to stores all Persistence class properties in one table. Some Annotations like below must be used for mapping table per hierarchy strategy @Inheritance(strategy="InheritanceType.SINGLE_TABLE"), @DiscriminatorColumn @DiscriminatorValue
  • Create the project directory structure
  • Create persistence classes or POJO classes.
Payment.java [java] package com.itoolsinfo; import javax.persistence.Column; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; @Entity @Table(name="SalaryDetails") @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="paymentmode") @DiscriminatorValue(value="employee") public class Payment { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int paymentId; @Column(name="amount") 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; } } [/java] Here the developer created the class Payment and this class will be extended by other classes to extend the properties from this class, here the developer used set and get methods. Actually the purpose of Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, one can define get methods to access these variables, and set methods to modify them. The @Column annotation is utilized to indicate the points of interest of the segment to which a field or property will be mapped. CreditCard.java [java]package com.itoolsinfo; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue("creditcard") public class CreditCard extends Payment { @Column(name="cardNumber") private int cardNumber; @Column(name="cardType") private String cardType; public int getCardNumber() { return cardNumber; } public void setCardNumber(int cardNumber) { this.cardNumber = cardNumber; } public String getCardType() { return cardType; } public void setCardType(String cardType) { this.cardType = cardType; } } [/java] Here the class CreditCard is extending the payment class. The EJB 3 standard explanations are contained in the javax.persistence bundle, so we import this bundle as the initial step. Second we utilized the @Entity annotation to the class which denote this class as a entity bean, so it must have a no-contention constructor that is obvious with at any rate secured scope. DebititCard.java [java]package com.itoolsinfo; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @Entity @DiscriminatorValue("debitcard") public class DebitCard extends Payment { @Column(name="pinNumber") private int pinNumber; @Column(name="cardName") private String cardName; public int getPinNumber() { return pinNumber; } public void setPinNumber(int pinNumber) { this.pinNumber = pinNumber; } public String getCardName() { return cardName; } public void setCardName(String cardName) { this.cardName = cardName; } } [/java]
  • Configure the all POJO classes in configuration file.
hibernate.cfg.xml [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:@localhost:1521:XE</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="hibernate.hbm2ddl.auto">create</property> <property name="show_sql">true</property> <mapping class="com.itoolsinfo.Payment"/> <mapping class="com.itoolsinfo.CreditCard"/> <mapping class="com.itoolsinfo.DebitCard"/> </session-factory> </hibernate-configuration> [/xml]
Properties Description
hibernate.connection.driver_class The JDBC driver class.
hibernate.dialect This property makes Hibernate generate the suitable SQL for the picked database.
hibernate.connection.url The JDBC URL to the database instance.
hibernate.connection.username The database username.
hibernate.connection.password The database password.
hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool.
hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection.
  • Create the class and store all the POJO class properties in that class to perform all the database operations in one table.
SPLessons.java [java]package com.itoolsinfo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; public class SPLessons { public static void main(String args[]) { SessionFactory factory=new AnnotationConfiguration().configure().buildSessionFactory(); Session session=factory.openSession(); Payment payment=new Payment(); payment.setPaymentId(3); payment.setAmount(20000); CreditCard creditcard=new CreditCard(); creditcard.setCardNumber(5678); creditcard.setCardType("visa"); DebitCard debitcard=new DebitCard(); debitcard.setPinNumber(6785); debitcard.setCardName("KARUR VYSYA BANK"); Transaction transaction=session.beginTransaction(); session.save(payment); session.save(creditcard); session.save(debitcard); transaction.commit(); session.close(); System.out.println("Payment datails all are entered using annotations"); } } [/java] This class is used to perform database operations on the above operations. Output [sql]select * from SalaryDetails;[/sql]

Table Per Subclass

shape Description

If this inheritance strategy is selected then Hibernate will map the properties of a superclass into subclass table and properties of subclass into superclass table.
  1. While creating the tables into a database, a subclass table should have a foreign key column. Then Hibernate will create the relation between superclass table and subclass table.
  2. Into the Table Per Subclass, the discriminator column is not required.
  3. In mapping file, Joined-subclass tag has to be configured under the class tag.
  4. First take the superclass and subclasses.Superclass is inherited into two subclasses.
  5. One have to store the data in super class table and subclass tables.

shape Conceptual figure

shape Examples

  • Create the project directory structure.
  • Create the persistance classes(POJO classes).
Payment.java [java]package com.itoolsinfo; 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; } } [/java] CreditCard.java [java]package com.itoolsinfo; public class CreditCard extends Payment { private int cardNumber; private String cardType; public int getCardNumber() { return cardNumber; } public void setCardNumber(int cardNumber) { this.cardNumber = cardNumber; } public String getCardType() { return cardType; } public void setCardType(String cardType) { this.cardType = cardType; } } [/java] While creating the tables into a database, a subclass table should have a foreign key column. Then Hibernate will create the relation between superclass table and subclass table. DebitCard.java [java]package com.itoolsinfo; public class DebitCard extends Payment { private int pinNumber; private String cardName; public int getPinNumber() { return pinNumber; } public void setPinNumber(int pinNumber) { this.pinNumber = pinNumber; } public String getCardName() { return cardName; } public void setCardName(String cardName) { this.cardName = cardName; } } [/java]
  • To map the POJO classes in Mapping File.
payment.hbm.xml [xml]<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.itoolsinfo.Payment" table=" SalaryDetails" > <id name="paymentId" column="pid"> <generator class="increment"/> </id> <property name="amount" column="amount"/> <joined-subclass name="com.itoolsinfo.CreditCard" table="creditcarddetails"> <key column="paymentId"/> <property name="cardNumber" column="creditNumber"/> <property name="cardType" column="creditType" length="20"/> </joined-subclass> <joined-subclass name="com.itoolsinfo.DebitCard" table="debitcarddetails"> <key column="paymentId"/> <property name="pinNumber"/> <property name="cardName" length="20"/> </joined-subclass> </class> </hibernate-mapping> [/xml] The generator class is the sub element of id utilized to produce the unique identifier for the objects of persistence class. There are numerous generator classes characterized in the Hibernate Framework. All the generator classes actualizes the org.hibernate.id.IdentifierGenerator interface.
  • Configure the mapping file in Hibernate Configuration file.
hibernate.cfg.xml [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:@localhost:1521:XE</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="hibernate.hbm2ddl.auto">create</property> <property name="show_sql">true</property> <mapping class="com.itoolsinfo.Payment"/> <mapping class="com.itoolsinfo.CreditCard"/> <mapping class="com.itoolsinfo.DebitCard"/> </session-factory> </hibernate-configuration> [/xml]
Properties Description
hibernate.connection.driver_class The JDBC driver class.
hibernate.dialect This property makes Hibernate generate the suitable SQL for the picked database.
hibernate.connection.url The JDBC URL to the database instance.
hibernate.connection.username The database username.
hibernate.connection.password The database password.
hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool.
hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection.
  • Create the class and stores the all POJO classes objects.
SPLessons.java [java]package com.itoolsinfo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class SPLessons { public static void main(String args[]) { SessionFactory factory=new Configuration().configure().buildSessionFactory(); Session session=factory.openSession(); Payment payment=new Payment(); payment.setPaymentId(5); payment.setAmount(30000); CreditCard creditcard=new CreditCard(); creditcard.setCardNumber(45); creditcard.setCardType("visa"); DebitCard debitcard=new DebitCard(); debitcard.setPinNumber(6432); debitcard.setCardName("ANDHRA BANK"); Transaction transaction=session.beginTransaction(); session.save(payment); session.save(creditcard); session.save(debitcard); transaction.commit(); session.close(); System.out.println("Payment datails all are inserted using Table Per Subclass"); } } [/java] In this class database operations will be performed. Output
    [sql]select * from SalaryDetails;[/sql] [sql]select * from CreditCardDetails;[/sql] [sql]select * from DebitCardDetails;[/sql]
    Here annotations used are @Inheritance(strategy=InheritanceType.JOINED) annotation in super class.It is used for super class to inherit to all subclasses. @PrimaryKeyJoinColum annotation in subclass. It is used for the super class primary key column to map to subclass table and data will be stored in superclass.
    • Create the project directory structure.
    • Create the persistence classes or POJO classes.
    Payment.java [java]package com.itoolsinfo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; @Entity @Table(name="SalaryDetails") @Inheritance(strategy=InheritanceType.JOINED) public class Payment { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int paymentId; @Column(name="amount") 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; } } [/java] Every element bean will have an essential key, which you comment on the class with the @Id comment. The essential key can be a solitary field or a mix of different fields relying upon your table structure. As a matter of course, the @Id comment will naturally decide the most suitable essential key era technique to be utilized however you can abrogate this by applying the @GeneratedValue explanation which takes two parameters system and generator. CreditCard.java [java]package com.itoolsinfo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; @Entity @Table(name="CreditCardDetails") @PrimaryKeyJoinColumn(name="paymentId") public class CreditCard extends Payment { @Column(name="cardNumber") private int cardNumber; @Column(name="cardType") private String cardType; public int getCardNumber() { return cardNumber; } public void setCardNumber(int cardNumber) { this.cardNumber = cardNumber; } public String getCardType() { return cardType; } public void setCardType(String cardType) { this.cardType = cardType; } } [/java] The @Table annotation permits you to indicate the points of interest of the table that will be utilized to hold on the element in the database. The @Table annotation gives four traits, permitting you to abrogate the name of the table, its inventory, and its composition, and uphold exceptional imperatives on sections in the table. DebitCard.java [java]package com.itoolsinfo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; @Entity @Table(name="DebitCardDetails") @PrimaryKeyJoinColumn(name="paymentId") public class DebitCard extends Payment { @Column(name="pinNumber") private int pinNumber; @Column(name="cardName") private String cardName; public int getPinNumber() { return pinNumber; } public void setPinNumber(int pinNumber) { this.pinNumber = pinNumber; } public String getCardName() { return cardName; } public void setCardName(String cardName) { this.cardName = cardName; } } [/java]
    • Configure all POJO classes in Configuration file.
    hibernate.cfg.xml [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="hibernate.hbm2ddl.auto">create</property> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property> <!-- property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:XE</property--> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping class="com.itoolsinfo.Payment"/> <mapping class="com.itoolsinfo.CreditCard"/> <mapping class="com.itoolsinfo.DebitCard"/> </session-factory> </hibernate-configuration> [/xml]
    • Create the class and store all the POJO class objects in that class.
    SPLessons.java [java]package com.itoolsinfo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; public class SPLessons { public static void main(String args[]) { SessionFactory factory=new AnnotationConfiguration().configure().buildSessionFactory(); Session session=factory.openSession(); Payment payment=new Payment(); payment.setPaymentId(5); payment.setAmount(30000); CreditCard creditcard=new CreditCard(); creditcard.setCardNumber(45); creditcard.setCardType("visa"); DebitCard debitcard=new DebitCard(); debitcard.setPinNumber(6432); debitcard.setCardName("ANDHRA BANK"); Transaction transaction=session.beginTransaction(); session.save(payment); session.save(creditcard); session.save(debitcard); transaction.commit(); session.close(); System.out.println("Payment datails all are inserted in Table Per Subclass using Annotations"); } } [/java] Here database operations will be performed. Output [sql]select * from SalaryDetails;[/sql] [sql]select * from CreditCardDetails;[/sql] [sql]select * from DebitCardDetails;[/sql]

    Table Per Concrete class

    shape Description

    In Table Per Concrete class, super class properties and subclass properties are combined to store in subclass table.
    • In Mapping file, the union-subclass tag has to be configured under the class tag.
    • In Table Per Concrete class, any discriminator column or foreignkey column are not used in mapping file.
    • Payment class properties are stored in CreditCard class table and DebitCard class tables.

    shape Conceptual figure

    shape Examples

    • Create the project directory structure.
    • Create persistence classes or POJO classes.
    Payment.java [java]package com.itoolsinfo; 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; } } [/java] CreditCard.java [java]package com.itoolsinfo; public class CreditCard extends Payment { private int cardNumber; private String cardType; public int getCardNumber() { return cardNumber; } public void setCardNumber(int cardNumber) { this.cardNumber = cardNumber; } public String getCardType() { return cardType; } public void setCardType(String cardType) { this.cardType = cardType; } } [/java] Actually the purpose of Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, one can define get methods to access these variables, and set methods to modify them. CreditCard.java DebitCard.java [java]package com.itoolsinfo; public class DebitCard extends Payment { private int pinNumber; private String cardName; public int getPinNumber() { return pinNumber; } public void setPinNumber(int pinNumber) { this.pinNumber = pinNumber; } public String getCardName() { return cardName; } public void setCardName(String cardName) { this.cardName = cardName; } } [/java]
    • To map all POJO classes in mapping file,
    payment.hbm.xml [xml]<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.itoolsinfo.Payment" table=" SalaryDetails" > <id name="paymentId" column="pid"> <generator class="increment"/> </id> <property name="amount" column="amount"/> <union-subclass name="com.itoolsinfo.CreditCard" table="creditcarddetails"> <property name="cardNumber" column="creditNumber"/> <property name="cardType" column="creditType" length="20"/> </union-subclass> <union-subclass name="com.itoolsinfo.DebitCard" table="debitcarddetails"> <property name="pinNumber"/> <property name="cardName" length="20"/> </union-subclass> </class> </hibernate-mapping> [/xml] The generator class is the sub element of id utilized to produce the unique identifier for the objects of persistence class. There are numerous generator classes characterized in the Hibernate Framework. All the generator classes actualizes the org.hibernate.id.IdentifierGenerator interface.
    • Configure the mapping file in Configuration file.
    hibernate.cfg.xml [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="hibernate.hbm2ddl.auto">create</property> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property> <!-- property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:XE</property--> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="payment.hbm.xml"/> </session-factory> </hibernate-configuration> [/xml]
    • Create the SPLessons class and stores all the POJO class objects to perform the database operations.
    SPLessons.java [java] package com.itoolsinfo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class SPLessons { public static void main(String args[]) { SessionFactory factory=new Configuration().configure().buildSessionFactory(); Session session=factory.openSession(); Payment payment=new Payment(); payment.setPaymentId(6); payment.setAmount(40000); CreditCard creditcard=new CreditCard(); creditcard.setCardNumber(45); creditcard.setCardType("visa"); DebitCard debitcard=new DebitCard(); debitcard.setPinNumber(7890); debitcard.setCardName("SYNDICATE BANK"); Transaction transaction=session.beginTransaction(); session.save(payment); session.save(creditcard); session.save(debitcard); transaction.commit(); session.close(); System.out.println("Payment datails all are inserted in Table Per Concreteclass using Xml"); } } [/java] Database operations will be performed here. Output [sql]select * from CreditCardDetails;[/sql] [sql]select * from DebitCardDetails;[/sql]
    Here two annotations are used. 1. @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) specifies that table per concrete class strategy is being used. It should be used only in super class. 2. @AttributeOverrides defines that super class attributes will be overridden in subclass table. It is applied only for subclasses.
    • Create the project directory structure.
    • Create persistence classes or POJO classes.
    Payment.java [java]package com.itoolsinfo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; @Entity @Table(name="SalaryDetails") @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) public class Payment { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int paymentId; @Column(name="amount") 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; } }[/java] The @Id annotation will naturally decide the most suitable essential key era technique to be utilized however you can abrogate this by applying the @GeneratedValue explanation which takes two parameters system and generator. CreditCard.java [java]package com.itoolsinfo; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name="CreditCardDetails") @AttributeOverrides({@AttributeOverride(name="paymentId", column=@Column(name="paymentId")), @AttributeOverride(name="amount", column=@Column(name="amount"))}) public class CreditCard extends Payment { @Column(name="cardNumber") private int cardNumber; @Column(name="cardType") private String cardType; public int getCardNumber() { return cardNumber; } public void setCardNumber(int cardNumber) { this.cardNumber = cardNumber; } public String getCardType() { return cardType; } public void setCardType(String cardType) { this.cardType = cardType; } } [/java] The @Table annotation permits you to indicate the points of interest of the table that will be utilized to hold on the element in the database. The @Table annotation gives four traits, permitting you to abrogate the name of the table, its inventory, and its composition, and uphold exceptional imperatives on sections in the table. DebitCard.java [java]package com.itoolsinfo; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name="DebitCardDetails") @AttributeOverrides({@AttributeOverride(name="paymentId", column=@Column(name="paymentId")), @AttributeOverride(name="amount", column=@Column(name="amount"))}) public class DebitCard extends Payment { @Column(name="pinNumber") private int pinNumber; @Column(name="cardName") private String cardName; public int getPinNumber() { return pinNumber; } public void setPinNumber(int pinNumber) { this.pinNumber = pinNumber; } public String getCardName() { return cardName; } public void setCardName(String cardName) { this.cardName = cardName; } } [/java]
    • Configure all the POJO classes in Configuration file.
    hibernate.cfg.xml [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:@localhost:1521:XE</property> <property name="connection.username">system</property> <property name="connection.password">system</property> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="hibernate.hbm2ddl.auto">create</property> <property name="show_sql">true</property> <mapping class="com.itoolsinfo.Payment"/> <mapping class="com.itoolsinfo.CreditCard"/> <mapping class="com.itoolsinfo.DebitCard"/> </session-factory> </hibernate-configuration> [/xml]
    • Create the SPLessons class and store all POJO class objects to perform the database operatipons.
    SPLessons.java [java]package com.itoolsinfo; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; public class SPLessons { public static void main(String args[]) { SessionFactory factory=new AnnotationConfiguration().configure().buildSessionFactory(); Session session=factory.openSession(); Payment payment=new Payment(); payment.setPaymentId(3); payment.setAmount(20000); CreditCard creditcard=new CreditCard(); creditcard.setCardNumber(5678); creditcard.setCardType("visa"); DebitCard debitcard=new DebitCard(); debitcard.setPinNumber(6785); debitcard.setCardName("KARUR VYSYA BANK"); Transaction transaction=session.beginTransaction(); session.save(payment); session.save(creditcard); session.save(debitcard); transaction.commit(); session.close(); System.out.println("Payment datails all are entered in Table Per Concrete class using annotations"); } } [/java] Database operations will be performed here. Output [sql]select * from CreditCardDetails;[/sql] [sql]select * from DebitCardDetails;[/sql]

    Summary

    shape Key Points

    • Hibernate inheritance - Table per class mapping inheritance use discriminator column in the database.
    • Table per sub class mapping inheritance  will have a key element.
    • Table for concrete class mapping inheritance use new element.