Hibernate @Where注释不能用于继承

时间:2017-10-05 03:57:50

标签: java hibernate inheritance where-clause

我正在使用Hibernate 5.1.2

我遇到了一个意想不到的问题,我似乎无法解决这个问题。这是我的数据模型的摘要: enter image description here

dfip_project_version是我的超类表,dfip_appln_proj_version是我的子类表。 dfip_application包含dfip_appln_proj_version的列表。

我将其映射如下:

@Table(name = "DFIP_PROJECT_VERSION")
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class AbstractProjectVersion {
    @Id @GeneratedValue
    @Column(name = "PROJECT_VERSION_OID")
    Long oid;

    @Column(name = "PROJ_VSN_EFF_FROM_DTM")
    Timestamp effFromDtm;

    @Column(name = "PROJ_VSN_EFF_TO_DTM")
    Timestamp effToDtm;

    @Column(name = "PROJECT_VERSION_TYPE")
    @Type(type = "project_version_type")
    ProjectVersionType projectVersionType;
}


@Table(name = "DFIP_APPLN_PROJ_VERSION")
@Entity
class ApplicationProjectVersion extends AbstractProjectVersion {

    @OneToOne
    @JoinColumn(name = "APPLICATION_OID", nullable = false)
    Application application;

    public ApplicationProjectVersion() {
        projectVersionType = ProjectVersionType.APPLICATION;
    }
}

@Table(name = "DFIP_APPLICATION")
@Entity
class Application {

    @Id @GeneratedValue
    @Column(name = "APPLICATION_OID")
    Long oid;

    @OneToMany(mappedBy="application", orphanRemoval = true, fetch = FetchType.EAGER)
    @Fetch(FetchMode.SELECT)
    @Where(clause = "PROJ_VSN_EFF_TO_DTM is null")
    List<ApplicationProjectVersion> applicationVersions = [];
}

我正在使用@Where注释,以便仅使用ApplicationProjectVersion检索当前Application

这个问题是Hibernate假定我引用的列在dfip_appl_proj_version表中,当它实际上在超类表(dfip_project_version)上时。

这是我到目前为止尝试解决此限制的问题:

尝试1

我尝试将@Where注释放到AbstractProjectVersion超类上,如下所示:

@Table(name = "DFIP_PROJECT_VERSION")
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Where(clause = "PROJ_VSN_EFF_TO_DTM is null")
public abstract class AbstractProjectVersion {
    ...etc...
}

这没有做任何事情,因为在检索Application时似乎没有注意到WHERE子句。

尝试2

我在applicationVersions LAZY上制作了Application列表,并试图像这样手动映射latestVersion

@Table(name = "DFIP_APPLICATION")
@Entity
class Application {

    @Id @GeneratedValue
    @Column(name = "APPLICATION_OID")
    Long oid;

    @OneToMany(mappedBy="application", orphanRemoval = true, fetch = FetchType.LAZY)
    @Fetch(FetchMode.SELECT)
    List<ApplicationProjectVersion> applicationVersions = [];

    @ManyToOne
    @JoinColumnsOrFormulas([
        @JoinColumnOrFormula(formula = @JoinFormula(value = "(APPLICATION_OID)", referencedColumnName="APPLICATION_OID")),
        @JoinColumnOrFormula(formula = @JoinFormula(value = "(select apv.PROJECT_VERSION_OID from DFIP_PROJECT_VERSION pv, DFIP_APPLN_PROJ_VERSION apv where apv.PROJECT_VERSION_OID = pv.PROJECT_VERSION_OID and apv.APPLICATION_OID = APPLICATION_OID and pv.PROJ_VSN_EFF_TO_DTM is null)", referencedColumnName="PROJECT_VERSION_OID")),
    ])
    ApplicationProjectVersion latestVersion;
}

这导致Hibernate生成以下SQL(代码段):

from DFIP_APPLICATION this_ 
left outer join DFIP_APPLN_PROJ_VERSION applicatio2_ 
    on (this_.APPLICATION_OID)=applicatio2_.APPLICATION_OID and 
       (select apv.PROJECT_VERSION_OID from DFIP_PROJECT_VERSION pv, DFIP_APPLN_PROJ_VERSION apv 
        where apv.PROJECT_VERSION_OID = pv.PROJECT_VERSION_OID and apv.APPLICATION_OID = this_.APPLICATION_OID 
        and pv.PROJ_VSN_EFF_TO_DTM is null)=applicatio2_.PROJECT_VERSION_OID 

导致ORA-01799: a column may not be outer-joined to a subquery

如果我无法在我的连接公式中指定子查询,那么我无法手动加入超类......

尝试3

我注意到@JoinFormula的使用使得Hibernate注意到超级类上的@Where注释。所以我尝试了以下内容:

@Table(name = "DFIP_PROJECT_VERSION")
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Where(clause = "PROJ_VSN_EFF_TO_DTM is null")
public abstract class AbstractProjectVersion {
    ...etc...
}

@Table(name = "DFIP_APPLICATION")
@Entity
class Application {

    @Id @GeneratedValue
    @Column(name = "APPLICATION_OID")
    Long oid;

    @OneToMany(mappedBy="application", orphanRemoval = true, fetch = FetchType.LAZY)
    @Fetch(FetchMode.SELECT)
    List<ApplicationProjectVersion> applicationVersions = [];

    @ManyToOne
    @JoinFormula(value = "(APPLICATION_OID)", referencedColumnName="APPLICATION_OID")
    ApplicationProjectVersion latestVersion;
}

这生成了以下SQL(代码段):

from DFIP_APPLICATION this_ 
left outer join DFIP_APPLN_PROJ_VERSION applicatio2_ 
    on (this_.APPLICATION_OID)=applicatio2_.APPLICATION_OID and ( applicatio2_1_.PROJ_VSN_EFF_TO_DTM is null) 
left outer join DFIP_PROJECT_VERSION applicatio2_1_ on applicatio2_.PROJECT_VERSION_OID=applicatio2_1_.PROJECT_VERSION_OID 

这几乎是正确的!不幸的是,它不是有效的SQL,因为applicatio2_1_在下一行声明之前就被使用了:(。

现在我没有想法,所以任何帮助都会受到赞赏。有没有办法指定一个WHERE子句,只引入当前的ProjectVersion,而不删除我的继承结构?

Related Hibernate issue ticket

2 个答案:

答案 0 :(得分:0)

我有解决这个问题的方法。我必须承认,它最终比我希望的更麻烦,但它确实很有效。我在发帖前等了几个月,以确保没有问题,到目前为止,我没有遇到任何问题。

我的实体仍然完全按照问题中的说明进行映射,但我不得不使用有问题的@Where注释,而是使用@Filter注释:

public class Application {

    @OneToMany(mappedBy="application", orphanRemoval = true, fetch = FetchType.EAGER)
    @Cascade([SAVE_UPDATE, DELETE, MERGE])
    @Fetch(FetchMode.SELECT)

    // Normally we'd just use the @Where(clause = "PROJ_VSN_EFF_TO_DTM is null"), but that doesn't work with collections of
    // entities that use inheritance, as we have here.
    //
    // Hibernate thinks that PROJ_VSN_EFF_TO_DTM is a column on DFIP_APPLN_PROJ_VERSION table, but it is actually on the "superclass"
    // table (DFIP_PROJECT_VERSION). 
    //
    // B/c of this, we have to do the same thing with a Filter, which is defined on AbstractProjectVersion.
    // NOTE: This filter must be explicitly enabled, which is currently achieved by HibernateForceFiltersAspect 
    //
    @Filter(name="currentProjectVersionOnly", 
        condition = "{pvAlias}.PROJ_VSN_EFF_TO_DTM is null", 
        deduceAliasInjectionPoints=false, 
        aliases=[ @SqlFragmentAlias(alias = "pvAlias", table = "DFIP_PROJECT_VERSION") ]
    )
    List<ApplicationProjectVersion> projectVersions = [];

}

由于我们使用过滤器,我们还必须定义它:

// NOTE: This filter needs to be explicitly turned on with session.enableFilter("currentProjectVersionOnly");
// This is currently achieved with HibernateForceFiltersAspect
@FilterDef(name="currentProjectVersionOnly")

@Table(name = "DFIP_PROJECT_VERSION")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class AbstractProjectVersion  {

}

当然,我们必须启用它,因为Hibernate没有自动打开所有过滤器的设置。

为此,我创建了一个系统范围的Aspect,其工作是在每次调用任何DAO之前启用指定的过滤器:

/**
 * Enables provided Hibernate filters every time a Hibernate session is openned.
 * 
 * Must be enabled and configured explicitly from Spring XML config (i.e. no auto-scan here)
 *
 * @author Val Blant
 */
@Aspect
public class HibernateForceFiltersAspect {

    List<String> filtersToEnable = [];

    @PostConstruct
    public void checkConfig() throws Exception {
        if ( filtersToEnable.isEmpty() ) {
            throw new IllegalArgumentException("Missing required property 'filtersToEnable'");
        }
    }

    /**
     * This advice gets executed before all method calls into DAOs that extend from <code>HibernateDao</code>
     * 
     * @param jp
     */
    @Before("@target(org.springframework.stereotype.Repository) && execution(* ca.gc.agr.common.dao.hibernate.HibernateDao+.*(..))")
    public void enableAllFilters(JoinPoint jp) {
        Session session = ((HibernateDao)jp?.getTarget())?.getSession();

        if ( session != null ) {
            filtersToEnable.each { session.enableFilter(it) } // Enable all specified Hibernate filters
        }
    }

}

和相应的Spring配置:

<!-- This aspect is used to force-enable specified Hibernate filters for all method calls on DAOs that extend HibernateDao -->  
<bean class="ca.gc.agr.common.dao.hibernate.HibernateForceFiltersAspect">
    <property name="filtersToEnable">
        <list>
            <value>currentProjectVersionOnly</value>            <!-- Defined in AbstractProjectVersion -->
        </list>
    </property>
</bean>

你有它 - 多态@Where子句:)。

答案 1 :(得分:0)

由于您正在寻找具有继承关系的@Where,因此我假设您正在尝试全局应用某些SQL逻辑,也许休眠拦截器或SQL检查器将更适合此类需求