Hibernate enableFilter not working when loading entity by id

心不动则不痛 提交于 2019-12-01 21:32:38

This is not a bug, it's the intended behavior. I updated the Hibernate User Guide to make it more obvious.

The @Filter does not apply when you load the entity directly:

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

assertNotNull( account1 );
assertNotNull( account2 );

While it applies if you use an entity query (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();
}

So, as a workaround, use the entity query (JPQL, HQL, Criteria API) to load the entity.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!