0

I have two entities, one is Item, another Fruit. I want to implement first as super class of the other, and I want all the parameters from the super class to be inherited by its subclass.

Also I want, when building database to bind that superclass table and all its properties to the subclass table, i.e., if I create more subclasses, I don't want for all of them to write values which were supposed to be in super class.

How should I achieve this?

item.java

  @MappedSuperclass
  @DiscriminatorColumn(name="Item")
  @Inheritance(strategy = InheritanceType.JOINED)
  public abstract class Item implements java.io.Serializable
   {
      // here goes all values of the class Item
   }

fruit.java

   @Entity
   @PrimaryKeyJoinColumn(name="ART_ID")
   public class Fruit extends Item implements java.io.Serializable{
      // here goes proper values of this class 
   }

database.db

   create table Item
   (
    ITEM_ID          bigint not null auto_increment,
    ITEM_NAME         varchar(25) not null,
    );

   create table Fruit
    (
    FRUIT_DATEFROZEN date,
    );

);
Takarakaka
  • 279
  • 2
  • 4
  • 15

1 Answers1

1

I implemented something like the following for a complicated inheritance tree I have.

@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
public abstract class Item
{
    @Id
    Long id;

    String name;
}

@DiscriminatorValue("FRUIT")
@SecondaryTable( name = "fruit" )
public class NumberAnswer extends Item
{
    @Column(table = "fruit")
    Date frozen;
}

create table Item
(
  ID     bigint not null auto_increment,
  NAME   varchar(25) not null,
);

create table Fruit
(
  ID     bigint not null
  FROZEN date,
);
Community
  • 1
  • 1
Ransom Briggs
  • 3,025
  • 3
  • 32
  • 46
  • How should I then implement my db file?Should I have create table Item (ITEM_ID bigint not null auto_increment, ITEM_NAME varchar(25) not null, ); create table Fruit ( FRUIT_DATEFROZEN date, );or for each subclasses table I should have values of the superclass table like create table Fruit (ITEM_ID bigint not null auto_increment, ITEM_NAME varchar(25) not null, FRUIT_DF date, );create table Meat (ITEM_ID bigint not null auto_increment, ITEM_NAME varchar(25) not null, MEAT varchar(25), ); – Takarakaka Aug 29 '12 at 23:15
  • In the subclass tables, the ids do not increment since they will be the same id as the main table and you should probably add a foreign key from fruit.id => item.id – Ransom Briggs Aug 30 '12 at 14:09
  • I see! So I will have to make fruit_id which is foreign key to item_id! Great, just as I wanted, now will see if it works. :) – Takarakaka Aug 30 '12 at 18:59