1

I'm using spring boot and Hibernate. What I'm trying is to have a single table for Materials and one for Costs.

What I want to know is if there's a way to specify in a subclass of Cost the specific type of material (Subclass of Material) it should handle. In the end, what I will like is that in order to create a SpecificCost, a SpecificMaterial should be provided not just a general Material.

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Material {}

@Entity
public class SpecificMaterial extends Material {}

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Cost {
  @ManyToOne
  private Material material;
}

@Entity
public class SpecificCost extends Cost{
  /*
  * I want to be able to specify that the field "material"
  * that comes from the parent class
  * should be of type SpecificMaterial a subclass of Material
  */
}

I tried to solve this with generics but it's not possible to use genetics in mapped columns. I have also tried with every one of the inheritance schemes but I haven't been able to. Does anyone know if there's a way to accomplished what I'm trying here?

Andronicus
  • 25,419
  • 17
  • 47
  • 88
  • Why would you have the need for an object in code but not in the database? Would you need a specificmaterial table? Check this question, you might be looking for a discriminator: https://stackoverflow.com/questions/16772370/when-to-use-discriminatorvalue-annotation-in-hibernate – Omeri Sep 09 '21 at 00:41
  • 1
    Thanks for the comment. I am using Single Table inheritance for both Material and Cost, I know that I have to use discriminator values for that. What I want is a subclass of Cost to have as material a subclass of Material. So that in the DB, the record of a specificCost can only have as a foreign key a SpecificMaterial. – Melanie Orellana Sep 09 '21 at 01:13
  • This makes no sense. You can't have a foreign key to a discriminated entity i.e. the tuple (id, discriminator) unless you specify all join columns individually on `Cost`. The only reasonable foreign key is to just the id of the material in this case. Everything else is application logic and should be validated through your application. – Christian Beikov Sep 13 '21 at 13:44

0 Answers0