| I have a problem with @SecondaryTable annotation using hibernate. In my project i have 3 entity hierarchy, with 2 tables referenced. This is an example of the structure of my project problem @MappedSuperclass @Table(name = "TableA") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @IdClass(ClassA_Key.class) @DiscriminatorFormula(" CASE WHEN field_1a='ASD' THEN 'A' ELSE 'B' END ") public abstract class ClassA implements Serializable { @Id @Column(name = "code_a", insertable = false, updatable = false) private String code_a; @Id @Column(name = "company_a", insertable = false, updatable = false) private String company_a; @Column(name = "field_1a") private String field_1a; } @Entity(name = "MyEntity") @Table(name = "TableA") @SecondaryTable(name = "TableB", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "code_b", referencedColumnName = "code_a"), @PrimaryKeyJoinColumn(name = "company_b", referencedColumnName = "company_a") }) @DiscriminatorFormula(" CASE WHEN field_1a='ASD' THEN 'A' ELSE 'B' END ") public class ClassB extends ClassA { //other fields of TableA @Column(name = "field_2a") private String field_2a; // fields of TableB @Column(name = "field_1b") private String field_1b; @Column(name = "field_2b") private String field_2b; } @Entity(name = "MyEntity") @Table(name = "TableA") @SecondaryTable(name = "TableB", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "code_b", referencedColumnName = "code_a"), @PrimaryKeyJoinColumn(name = "company_b", referencedColumnName = "company_a") } ) @DiscriminatorValue("A") public class ClassC extends ClassB implements Serializable { //..other fields of TableB (same table as ClassB) @Column(name = "field_3b") private String field_3b; } My problem is that when i try to persist an instance of ClassC obj, hibernate execute 3 statements, as shown below: Object obj=new ClassC(); //..various setting of obj parameters //persist entityManager.persist(obj); entityManager.flush(); [DEBUG] 2017-10-18 17:28:55.951 o.h.SQL. - insert into TableA ('code_a', 'company_a', 'field_1a') VALUES (?,?,?) ... [DEBUG] 2017-10-18 17:28:56.062 o.h.SQL. - insert into TableB ('code_b', 'company_b', 'field_2a', 'field_1b', 'field_2b') values (?, ?, ?, ?, ?) .... [DEBUG] 2017-10-18 17:28:56.094 o.h.SQL. - insert into TableB ('code_b', 'company_b', 'field_3b') values (?, ?, ?) but as you can see hibernate tries to insert the same record 2 times in TableB. Note that i need to annotate both ClassB and ClassC with @Entity annotation because i use them in different enviroments. |