JPA/Hibernate inheritance with multiple levels and tables.

So I have this structure.

Table1 id field1 field2 discriminatorValue

Table2 id field3

Table3 id field4

And I want to use inheritance as follows.

public class T1  {

private int id;

private String field1;
private String field2;

@SecondaryTable(name = "Table2", pkJoinColumns = {@PrimaryKeyJoinColumn(name = "id",     referencedColumnName = "id")})
public class T2 extends T1 {

private String field3;

@SecondaryTable(name = "Table3", pkJoinColumns = {@PrimaryKeyJoinColumn(name = "id",     referencedColumnName = "id")})
public class T3 extends T2 {

private String field4;

What I'm finding is that when I try to save a T3 object the secondary table from T2 doesn't get included.



It looks like you're using the SINGLE_TABLE inheritance strategy but explicitly splitting off some properties in the subclasses into separate tables, rather than using the joined-subclass strategy.

This seems to be the standard approach to mixing inheritance strategies

See: How to mix inheritance strategies with JPA annotations and Hibernate?

Mapping multi-Level inheritance in Hibernate with Annotations

The one thing you might be missing is specifying which fields go to which columns. @SecondaryTable is not tied to the inheritance hierarchy - you can use it in a single class - and therefore you have to explicitly specify that a field in the child class is mapped to the secondary table.

Thus in T2 you probably need

private String field3;

and in T3

private String field4;

Good luck!

Need Your Help

clearing or set null to objects in java

java memory-management null deep-copy shallow-copy

I was recently looking into freeing up memory occupied by Java objects. While doing that I got confused about how objects are copied (shallow/deep) in Java and how to avoid accidently clearing/null...