1

我有一个问题,我有一个带有继承 TABLE_PER_CLASS 和三个子表 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;

然后我在 StationCompany 上搜索 findAll,hibernate 使用 union select 进行查询。我将只搜索 StationCompany 条目。

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

2 回答 2

3

问题是休眠映射。我认为从 Station 到 StationCompany 到 Station 的结构存在问题......我用额外的 Abstract @MappedSuperclass 类解决了这个问题。之后,休眠选择正确的表,不再选择联合。

@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 {
于 2014-06-23T05:55:14.977 回答
0

不要执行全部搜索。

在 Station 上创建 NamedQuery:

@NamedQuery(name="Station.findStationByType", 
            query="SELECT s FROM Station s WHERE TYPE(s) = :type")

然后在您的站层次结构的主要外观中:

public class StationFacade<Station>{
  @PersistenceContext("contextName")
  private EntityManager em;

  public List<Station> findAll(Class<? extends Station> stationType){
    return em.createNamedQuery("Station.findStationByType")
             .setParameter("type", stationType.getSimpleName())
             .getResultList();
  }
}
于 2014-06-20T12:43:49.290 回答