Spring学习--Spring JPA实体类如何抽取父类

2025-05-18 03:56:24

1、基于 Spring Initializr 创建一个SpringBoot应用,必要的依赖包括 Spring Data JPA, H2 数据库 还有 Lombok。工程生成后,导入到 Eclipse 中,并在 application.properties 添加如下配置:# create the table when application starts, # and drop the tables when application stopsspring.jpa.hibernate.ddl-auto=create-drop# output the formatted sql in the consolespring.jpa.properties.hibernate.show_sql=truespring.jpa.properties.hibernate.format_sql=true

Spring学习--Spring JPA实体类如何抽取父类
Spring学习--Spring JPA实体类如何抽取父类

2、创建两个实体类图示,两个实体类分别是 Coffee 和 Computer, 他们包含相同的成员变量有 :id, name, createTime, updateTime, 目前在这两个实体类中都包含了这些相同成员变量的定义。

Spring学习--Spring JPA实体类如何抽取父类
Spring学习--Spring JPA实体类如何抽取父类

3、运行SpringBoot启动类,观察控制台的输出从控制台的输出可以看出,Spring JPA 为我们定义的两个实体类均创建了对应的表结构,并且包含了所有的字段。

Spring学习--Spring JPA实体类如何抽取父类

4、抽取公共字段到父实体类中上述操作虽然没有问题,但两个实体类存在4个公共字段,通常在一个项目中,实体个数动辄数十上百个,这么多公共字段的重复定义的问题,亟待解决。我们定义一个Bas髫潋啜缅eEntity(基础实体类),包含所有实体的公共字段(图1示)。注意,基础实体类(即实体类的公共父类)必须通过注解 @MappedSuperclass 进行标注!

Spring学习--Spring JPA实体类如何抽取父类
Spring学习--Spring JPA实体类如何抽取父类

5、再次执行SpringBoot启动类,观察控制台的输出从控制台输出的建表SQL语句可以看出,基于实体类创建的表均包含了基础实体类中的字段,完全符合业务要求。

Spring学习--Spring JPA实体类如何抽取父类
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢