Friday, 26 December 2014

Inheritance : InheritanceType.JOINED


The InheritanceType.JOINED strategy creates a table for the root class of an inheritance structure, and a separate table for each inheriting class in the structure. The data of the root class table is not copied in the inheriting class tables.

package myFirstHibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Product {
  @Id
  @GeneratedValue(strategy = GenerationType.TABLE)
  int id;
  private int noOfProducts;

  public int getNoOfProducts() {
    return noOfProducts;
  }

  public void setNoOfProducts(int noOfProducts) {
    this.noOfProducts = noOfProducts;
  }
  
}

package myFirstHibernate;

import javax.persistence.Entity;

@Entity
public class Laptop extends Product {
  private String brand;
  private String model;
  
  public String getBrand() {
    return brand;
  }
  
  public void setBrand(String brand) {
    this.brand = brand;
  }
  
  public String getModel() {
    return model;
  }
  
  public void setModel(String model) {
    this.model = model;
  }
  
}

package myFirstHibernate;

import javax.persistence.Entity;

@Entity
public class Book extends Product{
  private String title;
  private String author;
  
  public String getTitle() {
    return title;
  }
  
  public void setTitle(String title) {
    this.title = title;
  }
  
  public String getAuthor() {
    return author;
  }
  
  public void setAuthor(String author) {
    this.author = author;
  }
  
}


hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

  <session-factory>
  
    <!--  Database Connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost/sample</property>
    <property name="connection.username">root</property>
    <property name="connection.password">tiger</property>
    
    <!-- Enable the logging of all the generated SQL statements to the console -->
    <property name="show_sql">true</property>
    
    <!-- Format the generated SQL statement to make it more readable, -->
    <property name="format_sql">false</property>
    
    <!-- Hibernate will put comments inside all generated SQL statements to hint what’s the generated SQL trying to do -->
    <property name="use_sql_comments">false</property>
    
    <!-- This property makes Hibernate generate the appropriate SQL for the chosen database. -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    
    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>
    
    <!-- mappings for annotated classes -->
    <mapping class="myFirstHibernate.Product" />
    <mapping class="myFirstHibernate.Book" />
    <mapping class="myFirstHibernate.Laptop" />
    
  </session-factory>
  
</hibernate-configuration>


package myFirstHibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class TestInheritance {
  
  /* Step 1: Create session factory */
  private static SessionFactory getSessionFactory() {
    Configuration configuration = new Configuration().configure();
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
    applySettings(configuration.getProperties());
    SessionFactory factory = configuration.buildSessionFactory(builder.build());
        return factory;
    }
  
  public static void main(String args[]){
    Product prod = new Product();
    Book book1 = new Book();
    Book book2 = new Book();
    Laptop laptop = new Laptop();
    
    prod.setNoOfProducts(2534);
    
    book1.setAuthor("eckhart tolle");
    book1.setNoOfProducts(1234);
    book1.setTitle("The Power of Now");
    
    book2.setAuthor("Tuesdays With Morrie");
    book2.setNoOfProducts(500);
    book2.setTitle("Mitch Albom");
    
    laptop.setBrand("Dell");
    laptop.setModel("Alienware 17 Laptop");
    laptop.setNoOfProducts(1000);
    
    /* To persist data */
    SessionFactory sessionFactory = getSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(prod);
    session.save(book1);
    session.save(book2);
    session.save(laptop);
    session.getTransaction().commit();
    session.close(); 
  }
}


Run TestInheritance class you will get output like below.
Hibernate: alter table Book drop foreign key FK_59gdwuxvrpwmle1muds5t18e4
Hibernate: alter table Laptop drop foreign key FK_rlptkyc14kdhu3tg9payjbebf
Hibernate: drop table if exists Book
Hibernate: drop table if exists Laptop
Hibernate: drop table if exists Product
Hibernate: drop table if exists hibernate_sequences
Hibernate: create table Book (author varchar(255), title varchar(255), id integer not null, primary key (id))
Hibernate: create table Laptop (brand varchar(255), model varchar(255), id integer not null, primary key (id))
Hibernate: create table Product (id integer not null, noOfProducts integer not null, primary key (id))
Hibernate: alter table Book add constraint FK_59gdwuxvrpwmle1muds5t18e4 foreign key (id) references Product (id)
Hibernate: alter table Laptop add constraint FK_rlptkyc14kdhu3tg9payjbebf foreign key (id) references Product (id)
Hibernate: create table hibernate_sequences ( sequence_name varchar(255),  sequence_next_hi_value integer )
Dec 22, 2014 2:28:34 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: select sequence_next_hi_value from hibernate_sequences where sequence_name = 'Product' for update
Hibernate: insert into hibernate_sequences(sequence_name, sequence_next_hi_value) values('Product', ?)
Hibernate: update hibernate_sequences set sequence_next_hi_value = ? where sequence_next_hi_value = ? and sequence_name = 'Product'
Hibernate: insert into Product (noOfProducts, id) values (?, ?)
Hibernate: insert into Product (noOfProducts, id) values (?, ?)
Hibernate: insert into Book (author, title, id) values (?, ?, ?)
Hibernate: insert into Product (noOfProducts, id) values (?, ?)
Hibernate: insert into Book (author, title, id) values (?, ?, ?)
Hibernate: insert into Product (noOfProducts, id) values (?, ?)
Hibernate: insert into Laptop (brand, model, id) values (?, ?, ?)


MySQL structures look like below.

mysql> describe product;
+--------------+---------+------+-----+---------+-------+
| Field        | Type    | Null | Key | Default | Extra |
+--------------+---------+------+-----+---------+-------+
| id           | int(11) | NO   | PRI | NULL    |       |
| noOfProducts | int(11) | NO   |     | NULL    |       |
+--------------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> describe book;
+--------+--------------+------+-----+---------+-------+
| Field  | Type         | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+-------+
| author | varchar(255) | YES  |     | NULL    |       |
| title  | varchar(255) | YES  |     | NULL    |       |
| id     | int(11)      | NO   | PRI | NULL    |       |
+--------+--------------+------+-----+---------+-------+
3 rows in set (0.01 sec)

mysql> describe laptop;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| brand | varchar(255) | YES  |     | NULL    |       |
| model | varchar(255) | YES  |     | NULL    |       |
| id    | int(11)      | NO   | PRI | NULL    |       |
+-------+--------------+------+-----+---------+-------+
3 rows in set (0.01 sec)

mysql> select * from product;
+----+--------------+
| id | noOfProducts |
+----+--------------+
|  1 |         2534 |
|  2 |         1234 |
|  3 |          500 |
|  4 |         1000 |
+----+--------------+
4 rows in set (0.00 sec)

mysql> select * from book;
+----------------------+------------------+----+
| author               | title            | id |
+----------------------+------------------+----+
| eckhart tolle        | The Power of Now |  2 |
| Tuesdays With Morrie | Mitch Albom      |  3 |
+----------------------+------------------+----+
2 rows in set (0.00 sec)

mysql> select * from laptop;
+-------+---------------------+----+
| brand | model               | id |
+-------+---------------------+----+
| Dell  | Alienware 17 Laptop |  4 |
+-------+---------------------+----+
1 row in set (0.00 sec)

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment