search
HomeJavajavaTutorialWhat are the different inheritance mapping strategies in Hibernate?

What are the different inheritance mapping strategies in Hibernate?

Sep 12, 2023 pm 10:41 PM
Strategyhibernateinheritance mapping

Inheritance mapping strategies are divided into three types -

  • Table for each class hierarchy

  • Table of each concrete class

  • Tables for each subclass

    In this article, we will discuss the table hierarchy for each class.

Table for each class hierarchy

  • Here, only one table is created for inheritance mapping. The disadvantage of this approach is that a large number of null values ​​are stored in the table.

  • @Inheritance(strategy=InheritanceType.SINGLE_TABLE), @DiscriminatorColumn and @DiscriminatorValue are the annotations used in this strategy.

  • @DiscriminatorColumn is used to create an additional column that identifies the hierarchy class.

Consider the following example to understand this -

What are the different inheritance mapping strategies in Hibernate?

Implementation steps -

  • Create entity classes and use appropriate annotations for them.

  • Write hibernate configuration file and add mapping class.

  • Write code to create data and store it in a table.

1. Create entity class

Car.java

package com.tutorialspoint;
@Entity
@Table(name = "car")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="category",discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value="car")
public class Car {
   @Id
   @GeneratedValue(strategy=GenerationType.AUTO)
   private int id;

   @Column(name = "name")
   private String name;
   @Column(name = "color")
   private String color;
   //Getters
   //Setters
}

Sports_Car.java

package com.tutorialspoint;
import javax.persistence.*;
@Entity
@DiscriminatorValue("sportscar")
public class Sports_Car extends Car{
   @Column(name="mileage")
   private int mileage;

   @Column(name="cost")
   private int cost;
   //Getters
   //Setters
}

Taxi_Car.java

package com.tutorialspoint;
import javax.persistence.*;
@Entity
@DiscriminatorValue("taxicar")
public class Taxi_Car extends Car{
   @Column(name="farePerKm")
   private int farePerKm;

   @Column(name="available")
   private boolean available;
   //Getters
   //Setters
}

2. Hibernate configuration file (hibernate.cfg.xml)

<!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>
      <!-- JDBC Database connection settings -->
      <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
      <property name="connection.url">jdbc:mysql://localhost:3306/demo?useSSL=false</property>
      <property name="connection.username">root</property>
      <property name="connection.password">root</property>
      <!-- JDBC connection pool settings ... using built-in test pool -->
      <property name="connection.pool_size">4</property>
      <!-- Echo the SQL to stdout -->
      <property name="show_sql">true</property>
      <!-- Select our SQL dialect -->
      <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
      <!-- Drop and re-create the database schema on startup -->
      <property name="hbm2ddl.auto">create-drop</property>
      <!-- name of annotated entity class -->
      <mapping class="com.tutorialspoint.Car"/>
      <mapping class="com.tutorialspoint.Sports_Car"/>
      <mapping class="com.tutorialspoint.Taxi_Car"/>
   </session-factory>
</hibernate-configuration>

3. Code to create table and store data

package com.tutorialspoint;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class StoreTest {
   public static void main(String args[]){
      SessionFactory sessionFactory = new Configuration()
         .configure("com/tutorialspoint/hibernate.cfg.xml")
         .buildSessionFactory();
      Session session=sessionFactory.openSession();
      Transaction t=session.beginTransaction();
      Car c1=new Car();
      c1.setName("Mercedes");
      c1.setColor("Black");
      
      Sport_Car c2=new Sport_Car();
      c2.setName("Porsche");
      c2.setColor("Red");
      c2.setMileage(20);
      c2.setCost(5000000);
      
      Taxi_Car c3=new Taxi_Car();
      c3.setName("Innova");
      c3.setColor("White");
      c3.setFarePerKm(7);
      c3.setAvailable(true);
      
      session.persist(c1);
      session.persist(c2);
      session.persist(c3);
      
      t.commit();
      session.close();
   }
}

MySQL table

What are the different inheritance mapping strategies in Hibernate?

The above is the detailed content of What are the different inheritance mapping strategies in Hibernate?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor