JPA ENTITY EXTEND

1. Overview

Relational databases don’t have a straightforward way to map class hierarchies onto database tables.

To address this, the JPA specification provides several strategies:

  • MappedSuperclass?– the parent classes, can’t be entities
  • Single Table – The entities from different classes with a common ancestor are placed in a single table.
  • Joined Table – Each class has its table, and querying a subclass entity requires joining the tables.
  • Table per Class – All the properties of a class are in its table, so no join is required.

Each strategy results in a different database structure.

Entity inheritance means that we can use polymorphic queries for retrieving all the subclass entities when querying for a superclass.

Since Hibernate is a JPA implementation, it contains all of the above as well as a few Hibernate-specific features related to inheritance.

2.?MappedSuperclass

Using the?MappedSuperclass?strategy, inheritance is only evident in the class but not the entity model.

Let’s start by creating a?Person?class that will represent a parent class:

@MappedSuperclass
public class Person {@Idprivate long personId;private String name;// constructor, getters, setters
}

Notice that this class no longer has an?@Entity?annotation, as it won’t be persisted in the database by itself.

Next, let’s add an?Employee?subclass:

@Entity
public class MyEmployee extends Person {private String company;// constructor, getters, setters 
}

In the database, this will correspond to one?MyEmployee?table with three columns for the declared and inherited fields of the subclass.

If we’re using this strategy, ancestors cannot contain associations with other entities.

3. Single Table

The Single Table strategy creates one table for each class hierarchy.?JPA also chooses this strategy by default if we don’t specify one explicitly.

We can define the strategy we want to use by adding the?@Inheritance?annotation to the superclass:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class MyProduct {@Idprivate long productId;private String name;// constructor, getters, setters
}

The identifier of the entities is also defined in the superclass.

Then we can add the subclass entities:

@Entity
public class Book extends MyProduct {private String author;
}
@Entity
public class Pen extends MyProduct {private String color;
}

3.1. Discriminator Values

Since the records for all entities will be in the same table,?Hibernate needs a way to differentiate between them.

By default, this is done through a discriminator column called?DTYPE?that has the name of the entity as a value.

To customize the discriminator column, we can use the?@DiscriminatorColumn?annotation:

@Entity(name="products")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="product_type", discriminatorType = DiscriminatorType.INTEGER)
public class MyProduct {// ...
}

Here we’ve chosen to differentiate?MyProduct?subclass entities by an?integer?column called?product_type.

Next, we need to tell Hibernate what value each subclass record will have for the?product_type?column:

@Entity
@DiscriminatorValue("1")
public class Book extends MyProduct {// ...
}
@Entity
@DiscriminatorValue("2")
public class Pen extends MyProduct {// ...
}

Hibernate adds two other predefined values that the annotation can take —?null?and?not null:

  • @DiscriminatorValue(“null”)?means that any row without a discriminator value will be mapped to the entity class with this annotation; this can be applied to the root class of the hierarchy.
  • @DiscriminatorValue(“not null”)?– Any row with a discriminator value not matching any of the ones associated with entity definitions will be mapped to the class with this annotation.

Instead of a column, we can also use the Hibernate-specific?@DiscriminatorFormula?annotation to determine the differentiating values:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorFormula("case when author is not null then 1 else 2 end")
public class MyProduct { ... }

This strategy has the advantage of polymorphic query performance since only one table needs to be accessed when querying parent entities.

On the other hand, this also means that?we can no longer use?NOT NULL?constraints on subclass?entity properties.

4. Joined Table

Using this strategy, each class in the hierarchy is mapped to its table.?The only column that repeatedly appears in all the tables is the identifier, which will be used for joining them when needed.

Let’s create a superclass that uses this strategy:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Animal {@Idprivate long animalId;private String species;// constructor, getters, setters 
}

Then we can simply define a subclass:

@Entity
public class Pet extends Animal {private String name;// constructor, getters, setters
}

Both tables will have an?animalId?identifier column.

The primary key of the?Pet?entity also has a foreign key constraint to the primary key of its parent entity.

To customize this column, we can add the?@PrimaryKeyJoinColumn?annotation:

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/11456.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/11456.shtml
英文地址,請注明出處:http://en.pswp.cn/web/11456.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

webpack處理js和css模塊化導入導出示例:

webpack默認并不能處理js模塊化的導入和導出,依賴于ts-loader和babel-loader webpack.config,js module.exports {entry: ./src/index.ts,output: {filename: main.js,},mode: development, // 或者 productionmodule: {rules: [{test: /\.ts/,exclude: /(node_modules)/,use:…

二維平移矩陣 (2D translate matrix)

2D translate matrix 推薦閱讀正文推薦閱讀 矢量旋轉矩陣 正文 之前我們介紹了矢量旋轉矩陣的形式,這里我們來介紹一下平移矩陣的形式。比如,我們我們有一個點,其坐標為 (0,1)。那么我們如何操作才能夠將這個點沿著 x 軸正方向平移 1 個單位長度呢? 這里我們以向右移動…

vj題單 P4552 [Poetize6] IncDec Sequence

思路: 一次操作:選一個區間[l, r],把這個區間的數都加1或者都減1,可以將求該數列的差分數組b然后來進行該操作 一次操作的兩種種情況:(l可以等于r) 1.b[l]1 b[r1]-1 2.b[l]-1 b[r1]1 Q1:…

PHP 提取數組中的特定的值

需求: 前端展示: (1)之前的頁面: (2)修改后的頁面: 之前接口返回的數據 : 解決辦法:提取tags 中的 ’約 的數組 添加到一個新的數組中去 1:一開…

【CPP】多線程并發—— Mutex 和 Lock

#include <iostream> #include <thread> #include <mutex> #include "my_utils.h"std::mutex mtx; // 全局互斥鎖 int shared_data 0; // 共享數據 void increment() { for (int i 0; i < 10; i) { std::cout <<"incre…

2024年去除視頻水印的5種方法

如果你從事電影剪輯或者視頻編輯工作&#xff0c;你經常需要從優酷、抖音、TikTok下載各種視頻片段……。 通常這些視頻帶有水印和字幕。一些免費軟件如CapCut、canva、Filmora也會給你制作的視頻打上水印&#xff0c;這些水印嵌入在視頻內部。 2024年去除視頻水印的5種方法 …

Mysql-用戶變量的聲明與使用

#聲明變量 #1.標識符不能以數字開頭 #2.只能使用_或$符號&#xff0c;不能使用其他符號 #3.不能使用系統關鍵字 setuserName劉德華; select userName:劉青云;#將賦值與查詢結合 #查詢變量、使用變量&#xff0c;匿名的時候建議加上as select userName as 讀取到的userName變量…

Golang面向對象編程(二)

文章目錄 封裝基本介紹封裝的實現工廠函數 繼承基本介紹繼承的實現字段和方法訪問細節多繼承 封裝 基本介紹 基本介紹 封裝&#xff08;Encapsulation&#xff09;是面向對象編程&#xff08;OOP&#xff09;中的一種重要概念&#xff0c;封裝通過將數據和相關的方法組合在一起…

java JOptionPane 介紹

JOptionPane是Java Swing庫中的一個類,用于創建對話框(Dialogs),以便與用戶進行交互。它提供了一種簡單的方式來顯示消息、警告、錯誤、輸入框等。 主要方法: showMessageDialog(Component parentComponent, Object message):顯示一個包含消息的對話框。showInputDialog…

2024OD機試卷-手機App防沉迷系統 (java\python\c++)

題目:手機App防沉迷系統 題目描述 智能手機方便了我們生活的同時,也侵占了我們不少的時間。 “手機App防沉迷系統”能夠讓我們每天合理地規劃手機App使用時間,在正確的時間做正確的事。 它的大概原理是這樣的: 在一天24小時內,可以注冊每個App的允許使用時段一個時間段只…

Java轉Kotlin調用JNI方法異常

一、背景 Java調用JNI方法時沒有任何問題&#xff0c;但是使用Java轉Kotlin以后出現了崩潰異常&#xff1a;A java_vm_ext.cc:597] JNI DETECTED ERROR IN APPLICATION: jclass has wrong type: 校驗參數后沒有任何變化&#xff0c;經過分析驗證找到解決方案 二、原因…

若依生成樹表和下拉框選擇樹表結構(在其他頁面使用該下拉框輸入)

1.數據庫表設計 生成樹結構的主要列是id列和parent_id列&#xff0c;后者指向他的父級 2.來到前端代碼生成器頁面 導入你剛剛寫出該格式的數據庫表 3.點擊編輯&#xff0c;來到字段 祖籍列表是為了好找到直接父類&#xff0c;不屬于代碼生成器方法&#xff0c;需要后臺編…

【XSRP軟件無線電】基于軟件無線電平臺的QPSK頻帶通信系統設計

目錄&#xff1a; 目錄&#xff1a; 一、緒論 1.1 設計背景 1.2 設計目的 二、系統總體方案 2.1 專題調研題目 2.2 調研背景 2.3 設計任務解讀 2.4 設計原理 2.4.1 原理框圖 2.4.2 功能驗證 三、軟件設計 3.1 程序解讀 3.2 程序設計 3.3 仿真結果&#xff1a; 四、程序代碼分析…

網絡基礎-SSH協議(思科、華為、華三)

SSH&#xff08;Secure Shell&#xff09;是一種用于安全遠程訪問和安全文件傳輸的協議。它提供了加密的通信通道&#xff0c;使得用戶可以在不安全的網絡上安全地遠程登錄到遠程主機&#xff0c;并在遠程主機上執行命令、訪問文件以及傳輸文件&#xff0c;本篇主要講解命令執行…

SpringAI集成本地AI大模型ollama(調用篇)非常簡單!!

一&#xff0c;前提準備本地ai模型 1&#xff0c;首先需要去ollama官網下載開源ai到本地 網址&#xff1a;Ollama 直接下載到本地&#xff0c;然后啟動ollama 啟動完成后&#xff0c;我們可以在cmd中執行ollama可以看到相關命令行 2&#xff0c; 下載ai moudle 然后我們需要…

基于C#開發web網頁模板流程-登錄界面

前言&#xff0c;首先介紹一下本項目將要實現的功能 &#xff08;一&#xff09;登錄界面 實現一個不算特別美觀的登錄窗口&#xff0c;當然這一步跟開發者本身的設計美學相關&#xff0c;像蒟蒻博主就沒啥藝術細胞&#xff0c;勉強能用能看就行…… &#xff08;二&#xff09…

【vector】迭代器

Vector的基本數據結構 可以看到end指向的是數組的最后一個元素&#xff1b; 那么在使用函數遍歷的時候就要注意這種清理&#xff1b; 比如計算一個數組前5個數字的最小值&#xff1b; vector<int> prices{2,1,4,2,0,52,12};auto iter_min min_element(prices.begin(),pr…

NSSCTF | [LitCTF 2023]我Flag呢?

這道題沒啥好說的&#xff0c;題目標簽為源碼泄露&#xff0c;我們直接CtrlU查看網頁源碼就能在最后找到flag 本題完

深入學習指針2

前言 hello,我又來了&#xff0c;今天有我繼續帶領大家深入的學習指針&#xff0c;通過上次的學習&#xff0c;我們已經了解到了指針的基本概念&#xff0c;指針如何使用&#xff0c;指針使用的益處&#xff0c;以及一些相關的概念&#xff0c;那今天我們就繼續深入的學習&am…

Vue3專欄項目 -- 二、自定義From組件(下)

需求分析&#xff1a; 現在我們還需要一個整體的表單在單擊某個按鈕的時候可以循環的驗證每個input的值&#xff0c;最后我們還需要有一個事件可以得到最后驗證的結果&#xff0c;從而進行下一步的操作 如下&#xff0c;我們應該有一個form表單包裹著全部的input表單&#xf…