What are the different inheritance mapping strategies in Hibernate?
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 -
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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. 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 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

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,

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

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.

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
