Search code examples
javahibernatejpatable-per-class

Hibernate JPA @Inheritance TABLE_PER_CLASS JpaRepository on Child entity union select all tables


i have the problem i have a base abstract Entity Station with Inheritance TABLE_PER_CLASS and three child Tables StationCompany StationAnalysis StationVariant

@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS )
public abstract class Station {

@Entity
public class StationCompany extends Station {

@ManyToOne(optional = false, fetch = FetchType.EAGER)
@Fetch(FetchMode.SELECT)
private Company company;

@Entity
public class StationAnalysis extends StationCompany {

@ManyToOne(optional = false, fetch = FetchType.EAGER)
@Fetch(FetchMode.SELECT)
private Analysis analysis;

@Entity
public class StationVariant extends StationAnalysis {

@ManyToOne(optional = false, fetch = FetchType.EAGER)
@Fetch(FetchMode.SELECT)
private Variant variant;

public interface IStationCompanyRepository extends JpaRepository<StationCompany, Long> {

@Service
public class StationService implements IStationService<StationCompany> {

    @Autowired
    IStationCompanyRepository stationCompanyRepository;

Then i search findAll on StationCompany, hibernate make a query with union select. i will search only for the StationCompany entrys.

select x from ( select a from StationCompany union select b from StationVariant union select c from StationAnalysis )

Solution

  • the problem was the hibernate mapping. i think had a problem with the structure from Station to StationCompany to Station... I solve the problem with aditional Abstract @MappedSuperclass classes. After that the hibernate select the correct table and no more union selects.

    @MappedSuperclass
    @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
    public abstract class Station {
    
    @MappedSuperclass
    public abstract class AbstractStationCompany extends Station {
        @ManyToOne(optional = false, fetch = FetchType.EAGER)
        @Fetch(FetchMode.SELECT)
        private Company company;
    
    @Entity
    public class StationCompany extends AbstractStationCompany {
    
    @MappedSuperclass
    public class AbstractStationAnalysis extends AbstractStationCompany {
        @ManyToOne(optional = false, fetch = FetchType.EAGER)
        @Fetch(FetchMode.SELECT)
        private Analysis analysis;
    
    @Entity
    public class StationAnalysis extends AbstractStationAnalysis {
    
    @Entity
    public class StationVariant extends AbstractStationAnalysis {