Table of Contents
Table for each class hierarchy
1. Create entity class
Car.java
Sports_Car.java
Taxi_Car.java
2. Hibernate configuration file (hibernate.cfg.xml)
3. Code to create table and store data
MySQL table
Home Java javaTutorial What are the different inheritance mapping strategies in Hibernate?

What are the different inheritance mapping strategies in Hibernate?

Sep 12, 2023 pm 10:41 PM
Strategy hibernate inheritance 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
}
Copy after login

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
}
Copy after login

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
}
Copy after login

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>
Copy after login

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();
   }
}
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Key points of price strategy and promotion design in PHP flash sale system Key points of price strategy and promotion design in PHP flash sale system Sep 19, 2023 pm 02:18 PM

Key points of price strategy and promotion design in PHP flash sale system In a flash sale system, price strategy and promotion design are very important parts. Reasonable price strategies and well-designed promotions can attract users to participate in flash sale activities and improve the user experience and profitability of the system. The following will introduce the key points of price strategy and promotional activity design in the PHP flash sale system in detail, and provide specific code examples. 1. Key points in price strategy design: Determine the benchmark price: In the flash sale system, the benchmark price refers to the price of the product when it is normally sold. exist

How to integrate Hibernate in SpringBoot project How to integrate Hibernate in SpringBoot project May 18, 2023 am 09:49 AM

Integrating Hibernate in SpringBoot Project Preface Hibernate is a popular ORM (Object Relational Mapping) framework that can map Java objects to database tables to facilitate persistence operations. In the SpringBoot project, integrating Hibernate can help us perform database operations more easily. This article will introduce how to integrate Hibernate in the SpringBoot project and provide corresponding examples. 1.Introduce dependenciesIntroduce the following dependencies in the pom.xml file: org.springframework.bootspring-boot-starter-data-jpam

exe to php: an effective strategy to achieve function expansion exe to php: an effective strategy to achieve function expansion Mar 04, 2024 pm 09:36 PM

EXE to PHP: An effective strategy to achieve function expansion. With the development of the Internet, more and more applications have begun to migrate to the web to achieve wider user access and more convenient operations. In this process, the demand for converting functions originally run as EXE (executable files) into PHP scripts is also gradually increasing. This article will discuss how to convert EXE to PHP to achieve functional expansion, and give specific code examples. Why Convert EXE to PHP Cross-Platformness: PHP is a cross-platform language

Java Errors: Hibernate Errors, How to Handle and Avoid Java Errors: Hibernate Errors, How to Handle and Avoid Jun 25, 2023 am 09:09 AM

Java is an object-oriented programming language that is widely used in the field of software development. Hibernate is a popular Java persistence framework that provides a simple and efficient way to manage the persistence of Java objects. However, Hibernate errors are often encountered during the development process, and these errors may cause the program to terminate abnormally or become unstable. How to handle and avoid Hibernate errors has become a skill that Java developers must master. This article will introduce some common Hib

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

Full analysis of CentOS7 software installation steps and strategies Full analysis of CentOS7 software installation steps and strategies Jan 04, 2024 am 09:40 AM

I started to officially come into contact with Linux in 2010. The entry-level distribution was Ubuntu10.10, and later transitioned to Ubunu11.04. During this period, I also tried many other mainstream distributions. After entering the laboratory, I started using CentOS5, then CentOS6, and now it has evolved to CentOS7. I have been using Linux for four years. The first three years were spent messing around, wasting a lot of time, and gaining a lot of experience and lessons. Maybe I am really old now and am no longer willing to bother with it. I just hope that after configuring a system, I can continue to use it. Why write/read this article? When using Linux, especially CentOS, you will encounter some pitfalls, or some things that people with mysophobia can't tolerate: software from official sources

What are the differences between hibernate and mybatis What are the differences between hibernate and mybatis Jan 03, 2024 pm 03:35 PM

The differences between hibernate and mybatis: 1. Implementation method; 2. Performance; 3. Comparison of object management; 4. Caching mechanism. Detailed introduction: 1. Implementation method, Hibernate is a complete object/relational mapping solution that maps objects to database tables, while MyBatis requires developers to manually write SQL statements and ResultMap; 2. Performance, Hibernate is possible in terms of development speed Faster than MyBatis because Hibernate simplifies the DAO layer and so on.

What is the mapping method of one-to-many and many-to-many relationships in Java Hibernate What is the mapping method of one-to-many and many-to-many relationships in Java Hibernate May 27, 2023 pm 05:06 PM

Hibernate's one-to-many and many-to-many Hibernate is an excellent ORM framework that simplifies data access between Java applications and relational databases. In Hibernate, we can use one-to-many and many-to-many relationships to handle complex data models. Hibernate's one-to-many In Hibernate, a one-to-many relationship means that one entity class corresponds to multiple other entity classes. For example, an order can correspond to multiple order items (OrderItem), and a user (User) can correspond to multiple orders (Order). To implement a one-to-many relationship in Hibernate, you need to define a collection attribute in the entity class to store

See all articles