2

Is it possible to save a generic child??

e.g:

if i have a parent

    @Entity
    @Table(name = "parent")
    @Data
    @NoArgsConstructor
    class Parent<C>{

       @Id
       @GeneratedValue
       private long id;
    
       private C child;
    
    }

and 2 childs

    @Entity
    @Table(name = "child1")
    @Data
    @NoArgsConstructor
    class Child1{
       @Id
       @GeneratedValue
       private long id;

        private String message;

   }
    @Entity
    @Table(name = "child2")
    @Data
    @NoArgsConstructor
    class Child2{

       @Id
       @GeneratedValue
       private long id;

       private float age;

    }

so i will pass weather it's child1 and child2 during run time , will i be able to save them during run time?? if yes how?

1 Answers1

0

Take a look at the @MappedSuperclass and InheritanceType.SINGLE_TABLE annotations. To achieve exactly what you're after you'll have to use one of those two inheritance strategies in the code so that the tables map correctly.

Some examples: https://www.baeldung.com/hibernate-inheritance

Also: JPA: Implementing Model Hierarchy - @MappedSuperclass vs. @Inheritance

Joe W
  • 2,773
  • 15
  • 35