5

I have an entity:

@Entity
@Table(name = "[Usermaster]")
@Where(clause = "isDeleted = 0")
public class User {
//...
}

in some flow I need to ignore @Where annotation and get user even if isDeleted is not 0. How can I make it? (I use CRUD repositories to query)

Evgeny Makarov
  • 1,417
  • 1
  • 21
  • 41

2 Answers2

7

There is a dynamic version of the @Where setting, it is the @Filter. See:

Hibernate has the ability to pre-define filter criteria and attach those filters at both a class level and a collection level. A filter criteria allows you to define a restriction clause similar to the existing "where" attribute available on the class and various collection elements.

Management of @Filter is a bit more complex, in a nutshell:

  • <filter-def> / @FilterDef is needed to define filter
  • <filter> / @Filter must be assigned to class or a set
  • filter must be enabled on a session level, e.g.: session.enableFilter("myFilter").setParameter("myFilterParam", "some-value");

So, this, while being a bit more complex, provides exactly what we need: dynamic @Where to be turned on/off in run-time

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • @Filter is turned off by default so in order to apply it allover the system I'll need to add code in many places. I'm looking for transparent solution so I'll be able to add new code only for a few cases when I don't need the filter – Evgeny Makarov Jul 09 '14 at 17:31
  • 2
    Yes, `@Filter` management is a bit more challenging. On the other hand this is the way - the only way - how to evaluate `@Where` dynamcially. I.e. `@where` is a fixed mapping. No way how to turn it off. I know that it is not as nice answer as you wanted... but on the other hand, **my experinece with filter like this, is really good**. With some **AOP** in place, it is **enabled automatically** for us... let's say 99% cases. If needed, we can turn it off..and that works ;) – Radim Köhler Jul 09 '14 at 17:33
  • Thanks for your answer I've tried to find a way to find the code where new session is created by spring-data in order to figure out how I can override it and put my code that enables the @Filter, but I didn't succeed. – Evgeny Makarov Jul 09 '14 at 19:02
6

Old question, but the answer might be here:

simple solution is to use native SQL:

lst = sessionFactory.getCurrentSession().
createSQLQuery("select {entb.*}  from EntityB entb where  is_deleted=1")                            
       .addEntity("entb", EntityB.class)
       .list();
Community
  • 1
  • 1
Alejandro
  • 766
  • 9
  • 24