Search code examples
springinheritancespring-data-jpatable-per-class

Using JPARepository on Entity with Inheritancetype.TABLE_PER_CLASS result in wrong query


I've defined 2 entities in my project using the inheritance type "TABLE_PER_CLASS". After that I've defined 2 repositories to access data but, when I use them to find records for the B entity, the query generated does not include a JOIN statement but only "SELECT id, name, alternate_name from b" and it fails because "name" field does not exists.

Did I miss something that I can't see?

Entity A:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "a")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public abstract class A implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Column(name = "name")
    private String name;

    ...
    ...
}

Entity B:

@Entity
@Table(name = "b")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class B extends A implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Column(name = "alternate_name")
    private String alternateName;

    ...
    ...
}

BaseRepository:

@SuppressWarnings("unused")
@NoRepositoryBean
public interface BaseRepository<T extends A> extends JpaRepository<T, Long> {

}

ARepository:

@SuppressWarnings("unused")
@Repository
public interface ARepository extends BaseRepository<A> {

}

BRepository:

@SuppressWarnings("unused")
@Repository
public interface BRepository extends BaseRepository<B> {

}

Solution

  • I assume that you have a table a and a table b.

    But TABLE_PER_CLASS will only generate/use a table per concrete subclass. In your case just table b.

    If you want table a and b you must use the JOINED strategy.