【问题标题】:Hibernate enableFilter not working when loading entity by id通过 id 加载实体时休眠 enableFilter 不起作用
【发布时间】:2017-02-11 08:33:00
【问题描述】:

我有 3 个课程:

  • Event
  • PublicEvent extends Event
  • PersonalEvent extends Event

我的休眠映射文件如下所示。我想为PersonalEvent 添加一个过滤器,在加载这个对象之前,我启用了过滤器。但这不起作用。我的休眠版本是4.3.11.Final

Event.hbm.xml

<hibernate-mapping>
    <class name="org.calendar.Event">
        ...
        <filter name="personalEventAuthorize" condition="person_ID = :personId" />
    </class>
    <joined-subclass name="org.calendar.PersonalEvent" extends="org.calendar.Event">
        <key column="id" property-ref="id" />
        ...
        <many-to-one name="person" column="person_ID" entity-name="org.person.Person" />
     </joined-subclass>
     <joined-subclass name="org.calendar.PublicEvent" extends="org.calendar.Event">
        <key column="id" property-ref="id" />
        ...
     </joined-subclass>
     <filter-def name="personEventAuthorize">
        <filter-param name="personId" type="integer" />
     </filter-def>
</hibernate-mapping>

PersonalEventRepository

@Override
public PersonalEvent load(Long id) {
    Filter filter = getSession().enableFilter("personEventAuthorize");
    filter.setParameter("personId", getAuthenticatedPersonId());
    return super.loadById(id);
}

休眠生成的 SQL 查询没有我的过滤器。我的问题是什么?为什么休眠不能为加入的子类启用过滤器? 谢谢大家...

【问题讨论】:

    标签: java hibernate orm nhibernate-mapping hibernate-filters


    【解决方案1】:

    This is not a bug, it's the intended behavior。我更新了 Hibernate 用户指南以使其更加明显。

    直接加载实体时@Filter不适用:

    Account account1 = entityManager.find( Account.class, 1L );
    Account account2 = entityManager.find( Account.class, 2L );
    
    assertNotNull( account1 );
    assertNotNull( account2 );
    

    虽然它适用于您使用实体查询(JPQL、HQL、Criteria API):

    Account account1 = entityManager.createQuery(
        "select a from Account a where a.id = :id", 
        Account.class)
        .setParameter( "id", 1L )
    .getSingleResult();
    assertNotNull( account1 );
    try {
        Account account2 = entityManager.createQuery(
            "select a from Account a where a.id = :id", 
            Account.class)
        .setParameter( "id", 2L )
        .getSingleResult();
    }
    catch (NoResultException expected) {
        expected.fillInStackTrace();
    }
    

    因此,作为一种解决方法,使用实体查询(JPQL、HQL、Criteria API)来加载实体。

    【讨论】:

    • 这个问题似乎只存在于joined-subclass..!
    猜你喜欢
    • 2015-01-30
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多