JPA Mixed Inheritance Strategy

I have 3 objects:

@Entity public abstract class A { @Id public Long id; public String a1; public String a2; public String a3; //much more fields //getters and setters } @Entity public class B extends A { public String b1; public String b2; public String b3; //much more fields //getters and setters } @Entity public class C extends A { public String c; //that it. no more data //getters and setters } 

I want to match these classes on 2 tables. The first will contain all the data A and C (i.e., Inheritance SINGLE_TABLE ). The second will contain data B and a foreign key for A (i.e. JOINED inheritance).

I tried the suggested solution here , but this does not work for me. The attributes BB1 and BB2 also included in A

How to implement such a strategy? Classes A and C are different from dogs and cats, so I cannot combine them into one class.

Also I do not want to use a table for hierarchy, which will lead to duplication of a large amount of data A

+6
source share
2 answers

Having spent so much time on this and not having received an answer, I came to this solution (this may not be the best):

 @Entity public abstract class A implements Serializable { @Id public Long id; public String a1; public String a2; public String a3; //much more fields //getters and setters } @Entity public class B implements Serializable { @Id @Column(name="id", nullable=false) public Long id; @MapsId @OneToOne(optional=false) @JoinColumn(name="id") public A a; public String b1; public String b2; public String b3; //much more fields //getters and setters } @Entity public class C extends A { public String c; //that it. no more data //getters and setters } 

Conclusion
I was amazed at how well-supported and popular technologies like JPA did not offer a solution for such a trivial case. As Pascal Tivent pointed out in his answer to this question, Hibernate is deceiving us using a secondary table , which is a very tedious and error-prone approach (you must manually specify for each field which table it belongs to). So there seems to be still room for improvement in the JPA specification.

+1
source

JPA spec (paragraph 2.12) says that Support for the combination of inheritance strategies within a single entity inheritance hierarchy is not required by this specification . Keeping this in mind, in such cases I usually use the JOINED strategy for all of my entities.

+4
source

Source: https://habr.com/ru/post/898794/


All Articles