Hibernate Inheritance: Table Per Concrete Class

Hi Guys now its time to look at Table per concrete class hierarchy in hibernate. lets have a scenario where we have three classes Bike,BikeDetails and BikeEngine is the super class to the other two classes.In One Table per Concrete class scheme, each concrete class is mapped as normal persistent class. Thus we have 3 tables; Bike, BikeDetails and BikeEngine to persist the class data. In this scheme, the mapping of the subclass repeats the properties of the parent class.

Advantages
This is the easiest method of Inheritance mapping to implement.

Disadvantages
Data thats belongs to a parent class is scattered across a number of subclass tables, which represents concrete classes.
This hierarchy is not recommended for most cases.
Changes to a parent class is reflected to large number of tables
A query couched in terms of parent class is likely to cause a large number of select operations

following is the sql script to create the database.

DROP TABLE IF EXISTS `test`.`bike`;
CREATE TABLE  `test`.`bike` (
  `bike_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `bike_name` varchar(45) NOT NULL,
  `company` varchar(45) NOT NULL,
  PRIMARY KEY (`bike_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS `test`.`bike_details`;
CREATE TABLE  `test`.`bike_details` (
  `bike_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `bike_cost` int(10) unsigned NOT NULL,
  `manufacture_date` date NOT NULL,
  `bike_name` varchar(45) NOT NULL,
  `company` varchar(45) NOT NULL,
  PRIMARY KEY (`bike_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS `test`.`bike_engine`;
CREATE TABLE  `test`.`bike_engine` (
  `bike_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `engine_type` varchar(45) NOT NULL,
  `engine_cc` varchar(45) NOT NULL,
  `engine_bhp` varchar(45) NOT NULL,
  `bike_name` varchar(45) NOT NULL,
  `company` varchar(45) NOT NULL,
  PRIMARY KEY (`bike_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Following is the example where we map Bike, BikeDetails and BikeEngine entity classes using XML mapping.
Bike.java

/**
 * 
 */
package com.spark.hibernate.model;

import java.io.Serializable;

/**
 * @author Sony
 * 
 */
public class Bike implements Serializable {

	private int bikeId;
	private String bikeName;
	private String company;
	
	public Bike() {
		// TODO Auto-generated constructor stub
	}
	
	public Bike(String bikeName,String company) {
		this.bikeName = bikeName;
		this.company = company;
	}

	/**
	 * @return the bikeId
	 */
	public int getBikeId() {
		return bikeId;
	}

	/**
	 * @param bikeId
	 *            the bikeId to set
	 */
	public void setBikeId(int bikeId) {
		this.bikeId = bikeId;
	}

	/**
	 * @return the bikeName
	 */
	public String getBikeName() {
		return bikeName;
	}

	/**
	 * @param bikeName
	 *            the bikeName to set
	 */
	public void setBikeName(String bikeName) {
		this.bikeName = bikeName;
	}

	/**
	 * @return the company
	 */
	public String getCompany() {
		return company;
	}

	/**
	 * @param company
	 *            the company to set
	 */
	public void setCompany(String company) {
		this.company = company;
	}

}

BikeDetails.java

/**
 * 
 */
package com.spark.hibernate.model;

import java.io.Serializable;
import java.util.Date;

/**
 * @author Sony
 * 
 */
public class BikeDetails extends Bike implements Serializable {

	private int bikeCost;
	private Date manufactureDate;

	public BikeDetails() {
		// TODO Auto-generated constructor stub
	}

	public BikeDetails(String bikeName, String company, int bikeCost,
			Date manufactureDate) {
		super(bikeName, company);
		this.bikeCost = bikeCost;
		this.manufactureDate = manufactureDate;
	}

	/**
	 * @return the bikeCost
	 */
	public int getBikeCost() {
		return bikeCost;
	}

	/**
	 * @param bikeCost
	 *            the bikeCost to set
	 */
	public void setBikeCost(int bikeCost) {
		this.bikeCost = bikeCost;
	}

	/**
	 * @return the manufactureDate
	 */
	public Date getManufactureDate() {
		return manufactureDate;
	}

	/**
	 * @param manufactureDate
	 *            the manufactureDate to set
	 */
	public void setManufactureDate(Date manufactureDate) {
		this.manufactureDate = manufactureDate;
	}

}

BikeEngine.java

/**
 * 
 */
package com.spark.hibernate.model;

import java.io.Serializable;

/**
 * @author Sony
 * 
 */
public class BikeEngine extends Bike implements Serializable {

	private String engineType;
	private String engineBHP;
	private String engineCC;

	public BikeEngine() {
		// TODO Auto-generated constructor stub
	}

	public BikeEngine(String bikeName, String company, String engineType,
			String engineBHP, String engineCC) {
		super(bikeName, company);
		this.engineType = engineType;
		this.engineBHP = engineBHP;
		this.engineCC = engineCC;
	}

	/**
	 * @return the engineType
	 */
	public String getEngineType() {
		return engineType;
	}

	/**
	 * @param engineType
	 *            the engineType to set
	 */
	public void setEngineType(String engineType) {
		this.engineType = engineType;
	}

	/**
	 * @return the engineBHP
	 */
	public String getEngineBHP() {
		return engineBHP;
	}

	/**
	 * @param engineBHP
	 *            the engineBHP to set
	 */
	public void setEngineBHP(String engineBHP) {
		this.engineBHP = engineBHP;
	}

	/**
	 * @return the engineCC
	 */
	public String getEngineCC() {
		return engineCC;
	}

	/**
	 * @param engineCC
	 *            the engineCC to set
	 */
	public void setEngineCC(String engineCC) {
		this.engineCC = engineCC;
	}

}

lets construct a hbm file with multiple classes mappings as follows.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 17 Jun, 2013 9:42:56 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping package="com.spark.hibernate.model">

	<class name="Bike" table="BIKE">
		<id name="bikeId" type="int">
			<column name="BIKE_ID" />
			<generator class="native" />
		</id>
		<property name="bikeName" type="java.lang.String">
			<column name="BIKE_NAME" />
		</property>
		<property name="company" type="java.lang.String">
			<column name="COMPANY" />
		</property>
	</class>

	<class name="BikeDetails" table="BIKE_DETAILS">
		<id name="bikeId" type="int">
			<column name="BIKE_ID" />
			<generator class="native" />
		</id>
		<property name="bikeCost" column="bike_cost"></property>
		<property name="manufactureDate" column="manufacture_date"
			type="date"></property>
		<property name="bikeName" column="bike_name"></property>
		<property name="company" column="company"></property>
	</class>

	<class name="BikeEngine" table="BIKE_ENGINE">
		<id name="bikeId" type="int">
			<column name="BIKE_ID" />
			<generator class="native" />
		</id>
		<property name="engineType" column="engine_type"></property>
		<property name="engineCC" column="engine_cc"></property>
		<property name="engineBHP" column="engine_bhp"></property>
		<property name="bikeName" column="bike_name"></property>
		<property name="company" column="company"></property>
	</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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.password">root</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.query.startup_check">true</property>
  <property name="hibernate.show_sql">true</property>
  <property name="hibernate.use_sql_comments">true</property>
  <property name="hibernate.format_sql">true</property>
  
  <mapping resource="com/spark/hibernate/model/Bike.hbm.xml"/>
  
 </session-factory>
</hibernate-configuration>

Main.java

/**
 * 
 */
package com.spark.hibernate.main;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.spark.hibernate.model.Account;
import com.spark.hibernate.model.AccountHolder;
import com.spark.hibernate.model.AccountTransactions;
import com.spark.hibernate.model.Bike;
import com.spark.hibernate.model.BikeDetails;
import com.spark.hibernate.model.BikeEngine;
import com.spark.hibernate.util.HibernateUtil;

/**
 * @author Sony
 *
 */
public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Logger logger = LoggerFactory.getLogger(Main.class);
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		logger.info("-----------------Session created------------------");
		session.beginTransaction();
		logger.info("-----------------Transaction Started------------------");
		
		Bike bike = new Bike("R15", "Yamaha");
		session.persist(bike);
		logger.info("-------------Bike Object Persisted----------");
		
		BikeEngine bikeEngine = new BikeEngine("R15", "Yamaha","OilCooled","10.5","180");
		session.persist(bikeEngine);
		logger.info("-------------BikeEngine Object Persisted----------");
		
		BikeDetails bikeDetails = new BikeDetails("R15", "Yamaha",48000,new Date());
		session.persist(bikeDetails);
		logger.info("-------------BikeDetails Object Persisted----------");
		
		session.getTransaction().commit();
		logger.info("-----------------Transaction Commited------------------");
		session.close();
		logger.info("-----------------Session Closed------------------");
		sessionFactory.close();
		logger.info("-----------------SessionFactory Closed------------------");
		
	}

}

note:get the HibernateUtil from the previous posts
output:
Table_Per_Concrete_Class
That is it,
Happy Coding 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s