I have a webapp that is working with the following configuration (I changed the entity names):
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "animals")
public abstract class Animal { ...
@MappedSuperclass
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Mammal extends Animal { ...
@Entity
@Table(name = "mammals")
@PrimaryKeyJoinColumn(name = "mammal_id")
@DiscriminatorValue(value = "dog")
public class Dog extends Mammal { ...
@Entity
@Table(name = "mammals")
@PrimaryKeyJoinColumn(name = "mammal_id")
@DiscriminatorValue(value = "cat")
public class Cat extends Mammal { ...
So I have 2 tables: animals and mammals. This configuration is working, unless I don't completely understand how. The inheritance type is changed from JOINED to SINGLE_TABLE in Mammal, so cats and dogs are stored in mammals table joined with animals table by mammal_id column.
The problem is that is not possible to retrieve a mammal (cat or dog) in a polymorphic way:
Mammal mammal = (Mammal) hibernateTemplate.get(Mammal.class, id);
or a list of mammals (dogs and cats) with a single Hibernate query:
List<Mammal> list = (List<Mammal>) hibernateTemplate.find("from Mammal");
I get: "Unknown entity: Mammal", because Mammal is not an entity, it is just a mapped super class.
I tried several changes in configuration for example the one below. This seems to make sense, but in that case I got "Could not load entity: Mammal" because it looks for tables cats and dogs (which doesn't exist).
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "animals")
public abstract class Animal { ...
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "mammals")
@PrimaryKeyJoinColumn(name = "mammal_id")
@DiscriminatorColumn(name = "type")
public abstract class Mammal extends Animal { ...
@Entity
@DiscriminatorValue(value = "dog")
public class Dog extends Mammal { ...
@Entity
@DiscriminatorValue(value = "cat")
public class Cat extends Mammal { ...
So, to summarize: I want to keep the webapp working the same way (2 tables: animals and mammals) but at the same time be able to do a polymorphic query: retrieve a list of mammals (cats and dogs) with one query.
I hope I was clear enough and thanks in advance for any help.
ANOTHER TRY:
"Foreign key circularity dependency involving the following tables: "
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "animals")
public abstract class Animal { ...
@Entity
@Table(name = "mammals")
@PrimaryKeyJoinColumn(name = "mammal_id")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Mammal extends Animal { ...
@Entity
@Table(name = "mammals")
@DiscriminatorValue(value = "dog")
public class Dog extends Mammal { ...
@Entity
@Table(name = "mammals")
@DiscriminatorValue(value = "cat")
public class Cat extends Mammal { ...