Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

JPA 俩个实体类映射同一个表的问题

@Data
@Entity(name = "project")
public class ProjectA extends BaseEntity { ... }

@Data
@Entity(name = "project")
public class ProjectB extends BaseEntity { ... }

这样的情况,该如何处理。

相同启动会报:
Entities share the same JPA entity name: [project] which is not allowed!**

换成

@Data
@Entity(name = "project")
public class ProjectAEntity extends BaseEntity { ... }

@Data
@Entity(name = "project")
@Table(name = "project")
public class ProjectBEntity extends BaseEntity { ... }

报错

Not a managed type: class ...ProjectBEntity

查了很多,但是没什么实际上的效果,关于多个实体映射同一张表,有什么好的解决办法吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

看了你的描述,ProjectAEntity与ProjectBEntity应该有相同的字段,从面向对象的层面来讲,这两个类可以抽象一个基类,使用JPA的 单表继承策略 应该可以解决你的问题;使用JPA的好处之一就是既能够满足面向对象的设计实体,又很够很多策略的满足表的映射

单表继承策略:
多个Java实体映射到一张数据表,在表中通过一列辨别字段来区别不同类别的实体

a.在父类实体的@Entity注解下添加如下的注解:

@Inheritance(Strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name=”辨别字段列名”)
@DiscriminatorValue(父类实体辨别字段列值)

b.在子类实体的@Entity注解下添加如下的注解:

@DiscriminatorValue(子类实体辨别字段列值) 

具体的例子可以搜索一下,应该有很多


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...