javahibernatespring-data-jpahibernate-ogmhibernate-5

How to use generic type parameter with Hibernate 5?


Below are the class definition

interface

public interface myInterface{

    void myMethod1();

}

MyClass1 Class which implements above interface

 @Entity
 public class MyClass1 implements MyInterface{

    @Id
    private int id;
    private String field1;
    private String field2;

    // Getter and setter

}

MyClass2 Class which implements above interface

 @Entity
 public class MyClass2 implements MyInterface{

    @Id
    private int id;
    private String field3;
    private String field4;

    // Getter and setter

}

And finally the entity class which has a list with type parameter.

@Entity
public class MyClass{

    @Id
    priviate int id;
    private String field5;
    private String field6;
    private List<? extends MyInterface> mylist;

    //getter and setter

}

The generated class I'm looking at would look like something like below.

MyClass Table

-------------------------
id | field5 | field6
-------------------------
1  | abc    | def
2  | abc    | def
3  | abc    | def

MyClass1 Table

-------------------------
id | field1 | field2 | myclass_fk
-------------------------
1  | abc    | def    | 2
2  | abc    | def    | 2
3  | abc    | def    | 1

MyClass2 Table

-------------------------
id | field3 | field4 | myclass_fk
-------------------------
1  | abc    | def    | 3
2  | abc    | def    | 1
3  | abc    | def    | 1

I tried to use @OneToMany on the list with targetType to MyInterface but it failed with error not a entity class.

EDIT

Can it be achieved with Hibernate OGM, preferably using graph or Mongo (document) based?


Solution

  • I could achieve this using @ManyToAny annotation, though I needed to modify the class bit.