其他分享
首页 > 其他分享> > 通过ID加载实体时,Hibernate enableFilter不起作用

通过ID加载实体时,Hibernate enableFilter不起作用

作者:互联网

我有3节课:

>活动
> PublicEvent扩展事件
> PersonalEvent扩展事件

我的休眠映射文件就像下面这样.我想为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查询没有我的过滤器.我怎么了为什么休眠无法为连接子类启用过滤器?
谢谢大家…

解决方法:

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,标准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,标准API)来加载实体.

标签:orm,hibernate,nhibernate-mapping,hibernate-filters,java
来源: https://codeday.me/bug/20191111/2021919.html