domgom
domgom

Reputation: 413

JPA 2 Inheritance.TABLE_PER_CLASS with abstract relation

I have the following entities:

@Entity
public class Owner{
@Id
@Column(name = "OWNER_ID")

    @OneToMany()
    @JoinColumn(name = "OWNER_ID")
    private Set<Parent> parents;
    ...
}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Parent{
    @Id
    @Column(name = "PARENT_ID")
    ...
}

@Entity
public class ChildA extends Parent{
    ...
}

@Entity
public class ChildB extends Parent{
    ...
}

}

The problem is that I get the following exception when I try to persist a Owner with parent elements:

org.springframework.dao.InvalidDataAccessResourceUsageException: could not insert collection: [sample.Owner.parents#1]; SQL [update Parent set OWNER_ID=? where PARENT_ID=?]; org.springframework.dao.InvalidDataAccessResourceUsageException: could not insert collection: [sample.Owner.parents#1]; SQL [update Parent set OWNER_ID=? where PARENT_ID=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not insert collection: [sample.Owner.parents#1]nested exception is org.hibernate.exception.SQLGrammarException: could not insert collection: [sample.Owner.parents#1]

If I change InheritanceType to JOINED it works fine. Any ideas about why it's trying to persist the parent abstract class instead of the child specific ones?

Upvotes: 2

Views: 1556

Answers (1)

axtavt
axtavt

Reputation: 242786

Hibernate requires polymorphic associations to table-per-class hierarchies to be bidirectional (2.2.4.1. Table per class):

public class Owner {
    @OneToMany(mappedBy = "owner")
    private Set<Parent> parents;
    ...
}

public clas Parent {
    ...
    @ManyToOne
    @JoinColumn(name = "OWNER_ID")
    private Owner owner;
    ...
}

Upvotes: 2

Related Questions