Hibernate inheritance table per class and single table mix

1.6k Views Asked by At

I am developing online web shop, and I need help with Hibernate mapping. I have the following inheritance:

         BaseProduct
         /         \
     Guitar         Drum
     /    \         /    \
AcGuitar   ElGuitar AcDrum ElectricDrum

What I want:
1)Common fields such as id, name, description will be in @MappedSuperclass BaseProduct.
2)Musical instrument types (Guitar, Drum) will have common fields for these types of instruments.
3)At the end, concrete classes AvGuitar, ElGuitar etc will have unique properties for this concrete instruments.

The most problem is that I want that there will be two tables for two types of instruments: t_guitar and t_drum (InheritanceType.TABLE_PER_CLASS), and for concrete classes one table InheritanceType.SINGLE_TABLE, which means there will be one table for acoustic and electric guitar and one table for acoustic and electric drums with corresponding discriminant column.

How can I achieve that? Thanks!

Update 1

As I need to interact with the whole hierarchy as one general type and map products to another entities, I did the following:

@MappedSuperclass
public abstract class BaseProduct { //supercclass 

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private Long id;
    private String title;
    // etc
}

And medium class Product:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Product extends BaseProduct {
}

So, with this solutions any mixes unfortunately still don't work.

2

There are 2 best solutions below

2
On

You can do it something like...

    @MappedSuperclass
    public class base { 
    @Id
    private  String id;   //yr field

    }


    @Entity
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(
    name="classname",
    discriminatorType=DiscriminatorType.STRING
    )
    public class drum  extends base{

   String drumProperties;  //yr drum prop.

    }

    @Entity
    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(
    name="classname",
    discriminatorType=DiscriminatorType.STRING
    )
    public class guitar extends base {

    private String guitarProperties;    //guitar prop.
    }


    @Entity
    public class AcGuitar extends guitar{
    String acGuitarprop;

    }

   @Entity
   public class ElGuitar extends guitar{
   String elGuitarprop;

   }

    @Entity
   public class ElDrum extends drum{
   String elDrumprop;

   }

    @Entity

    public class AcDrum extends drum{
   String acDrumprop;

     }

on result u ll get two table in yr DB ,i. e. guitar and drum

0
On
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class base { 
@Id
private  String id;   //yr field

}

now there ll be three table in yr db .for your reference check out. here