简体   繁体   English

在Hibernate中映射具有多个ID的扩展实体

[英]Mapping extended entities with multiple ID's in Hibernate

I have implemented a db which is consisted of Article and Fruit tables, with the following specifications: 我已经实现了一个db,它由Article和Fruit表组成,具有以下规范:

create table Fruit
(
ART_ID            bigint,
FRU_ID          bigint not null auto_increment,
FRU_FROZEN   varchar(15),
primary key(FRU_ID)
);

# Implemented

create table Article
(
ART_ID            bigint,
ART_NAME         varchar(10) not null,
ART_COST   varchar(10) not null,
primary key(ART_ID)
);

alter table Fruits add constraint FK_FRUIT_ARTICLE foreign key (ART_ID) references Article (ART_ID) on delete restrict on update restrict; alter table Fruits添加约束FK_FRUIT_ARTICLE外键(ART_ID)引用删除限制更新限制条款(ART_ID);

and with following class entities : Article.java 以及以下类实体:Article.java

@Entity      
@Table(name = "Article")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Article implements Serializable
 {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
@Basic(optional = false)
@Column(name = "ART_ID")
private Long id;

@Basic(optional = false)
@Column(name = "ART_NAME")
private String name;

@Basic(optional = true)
@Column(name = "ART_COST")
private String cost; 

// constructors, getters and setters //构造函数,getter和setter

Fruit.java Fruit.java

@Entity
@Table(name="Fruit")
public class Fruit extends Article{


@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "FRU_ID")
private long fruitID;

@Basic(optional = false)
@Column(name = "FRU_FROZEN")
private String fruitFrozen;

// constructors, getters and setters //构造函数,getter和setter

Now, my problem is how to have ID in Article and in Fruit, if I keep it this way, it throws me exception that sub-class must not contain IDClass because it will result with multiple ID's. 现在,我的问题是如何在Article和Fruit中使用ID,如果我保持这种方式,它会抛出异常,即子类不能包含IDClass,因为它会产生多个ID。 Any help is appreciated. 任何帮助表示赞赏。 Thanks in advance. 提前致谢。

It means what it says, an Entity cannot have two IDs. 它意味着它所说的,实体不能拥有两个ID。

Consider the operation 考虑操作

entityManager.find(Article.class, 1l);

How is it supposed to know which one to return if there are two articles (an article and a fruit) that both have id 1? 如果有两篇文章(文章和水果)都有id 1,那该怎么知道要归还哪一篇?

If your tables need to each have IDs, entity inheritance is not an appropriate solution. 如果您的表需要每个都有ID,则实体继承不是合适的解决方案。 Consider putting the common elements in an @MappedSuperclass instead. 考虑将公共元素放在@MappedSuperclass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM