How to activate and deactivate Hibernate Filters

Assume you have hibernate filters you or somebody else have defined in the code for an entity.

For convenience lets take a short example for entity Resource:

@FilterDefs({@FilterDef(name = "nonDeletedResource")})
@Filters({@Filter(name = "nonDeletedResource", condition = "deleted = 0")})
public class Resource extends AbstractEntity {
...
}

The idea of the above hibernate filter is to give the option to retrieve only the entities that are not signed as deleted.

In our use case we want to activate the filters all the time so we activate the filter each time the session created:

Session session() {
	Session session = sessionFactory.getCurrentSession();
	session.enableFilter("nonDeletedResource");
	return session;
}

But then we have a use case we want the deleted entities as well, so we use the disableFiilter API to deactivate the filter in the specific session with the all entities query:

void getAllEntities (
        Session session = sessionFactory.getCurrentSession();
        if (withDeleted)
	        session.disableFilter("nonDeletedResource");
        ...
}

Any more questions or feedbacks are welcome!

Developer