I have implemented a db which is consisted of Article and Fruit tables, with the following specifications:
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;
and with following class entities :
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
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
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. Any help is appreciated. Thanks in advance.
It means what it says, an Entity cannot have two IDs.
Consider the operation
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?
If your tables need to each have IDs, entity inheritance is not an appropriate solution. Consider putting the common elements in an
@MappedSuperclassinstead.