JPA ENTITY EXTEND

2024-05-14 04:12
文章标签 jpa entity extend

本文主要是介绍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:

这篇关于JPA ENTITY EXTEND的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/987712

相关文章

使用Spring Boot集成Spring Data JPA和单例模式构建库存管理系统

引言 在企业级应用开发中,数据库操作是非常重要的一环。Spring Data JPA提供了一种简化的方式来进行数据库交互,它使得开发者无需编写复杂的JPA代码就可以完成常见的CRUD操作。此外,设计模式如单例模式可以帮助我们更好地管理和控制对象的创建过程,从而提高系统的性能和可维护性。本文将展示如何结合Spring Boot、Spring Data JPA以及单例模式来构建一个基本的库存管理系统

spring data jpa 懒加载问题

使用spring-data-jpa+spring+springmvc+restful的时候,碰到了一个问题,就是懒加载的问题。因为是后端返回的是JSON数据,所以如果在要额皮质懒加载的的关联字段的时候,只是配置 @ManyToOne(fetch=FetchType.LAZY)               @JoinColumn(name = "cat_measurement") 这样会报一个错误

Oracle - ORA-01652: unable to extend temp segment by 128 in tablespace TEMP

一、原因     意思是指TEMP表空间无法自动扩展TEMP段。这种问题一般有两种原因:一是临时表空间空间太小,二是不能自动扩展。 二、分析     查看TEMP表空间的数据文件个数,当前大小,是否自动扩展 SQL> SELECT TABLESPACE_NAME, FILE_NAME, BYTES/1024/1024 "CURR_SIZE(MB)", MAXBYTES/1024/102

SpringBoot(JPA关联)

JPA多表查询 多表查询在spring Data JPA 中有两种实现方式,第一种是创建一个结果集的接口来接收多表联接查询后的结果,第二种是利用JPA的关联映射来实现。 示例代码 多表联接查询 实体类Role @Entity@Table(name = "sys_role")@Datapublic class Role {@Id@GeneratedValue(strateg

list之extend方法的一个错误使用案例分析

直接上代码: >>> values = ['first']>>> values['first']>>> values.extend('second')>>> values['first', 's', 'e', 'c', 'o', 'n', 'd']>>> values.extend(['third'])>>> values['first', 's', 'e', 'c', 'o

swiper 源码笔记: Util中 extend的写法

const Util = {//判断是否是Object 类型isObject(o) {//typeof 等于object的也可能是null, 所以要加上 o !== null ; 后面两个条件是防止 new Date()等类型的object, 要判断它的构造函数return typeof o === 'object' && o !== null && o.constructor && o.con

了解Spring Data JPA

1、Spring Data JPA 1.1、概述         Spring Data JPA 是 Spring 基于JPA 规范的基础上封装的⼀套 JPA 应⽤框架,可使开发者⽤极简的代码即可实现对数据库的访问和操作。它提供了包括增删改查等在内的常⽤功能!学习并使⽤Spring Data JPA 可以极⼤提⾼开发效率。 Spring Data 家族: 1.2、官网 Spri

开发指南058-JPA多数据源

一般情况下,一个微服务只链接一个数据库,但是不排除有些情况下需要链多个库。链多个库比较复杂,介绍如下:        1、nocas中要配置多数据源              白框内为正常的单数据库情况。下面增加标识(可以任意起,这里为eva),然后跟数据库定义       2、定义新数据库源 @Configurationpublic class evaDruidCon

[转载] Java中extend 与 implement 区别

参考博客原址 https://blog.csdn.net/wm5920/article/details/9982057 简单说:  extends是继承父类,只要那个类不是声明为final或者那个类定义为abstract的就能继承,JAVA中不支持多重继承,但是可以用接口来实现,这样就要用到implements,继承只能继承一个类,但implements可以实现多个接口,用逗号分开就行了 比如

JPA关联MyBatis

3.1 JPA 多表查询        多表查询在 Spring Data JPA 中有两种实现方式,第一种是创建一个结果集的接口来接受多表连接查询后的结果,第二种是利用 JPA 的关联映射来实现 3.1.1 数据库表及关系       CRM 数据库中除 sys_user(用户)表外,还包括sys_role(角色)表。       sys_role(角色)表脚本: CREATE TAB