23

I have an Entity which has an association to another Entity annotated with @Where, like so

public class EntityA {

    @OneToMany
    @Where(...)
    private List<EntityB> entityBList;

}

Recently the inevitable has happened, I need to load EntityB's that don't conform to the @Where clause. I could remove the @Where annotation, but it is used a lot, so ideally I don't want to do that. Apart from loading the list of EntityB's manually, with another query, what are my options? Can I tell Hibernate to ignore the @Where annotation?

Zecrates
  • 2,952
  • 6
  • 33
  • 50

5 Answers5

26

I just had the same question. I solved the problem like this:

@Query(value="SELECT * FROM EntityA", nativeQuery=true)
public ignoreWhereMethod(){}

The SQL in the @Query annotation must point the table's name and the fields' names (not entity's name).

14

After lots of research it appears that this is simply impossible. I'd strongly suggest avoiding @Where, as it is hard to predict beforehand if you'll ever need those associations or not.

Zecrates
  • 2,952
  • 6
  • 33
  • 50
9

I know its an old question but in case anyone look for an answer...
I had the same dilemma, you don't want to mess your code with "is_deleted= false" every where you select,

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();
JavaSheriff
  • 7,074
  • 20
  • 89
  • 159
6

You can map another property with same data like this:

public class EntityA {

    @OneToMany
    @JoinColumn(name='theColumnName', insertable=false, updateable=false)
    private List<EntityB> entityBListReadOnly;

}

Important to set as updateable false and insertable falso to avoid consistency problems in your data!

Gabriel
  • 101
  • 1
  • 5
1

Another solution is filter, as explained in this question. Hibernate how to ignore @Where annotation

I will be trying this myself because the combination of @where and @NamedNativeQueries is a very cumbersome solution in our situation. But I do not know yet if @Filter is any better.

Björn
  • 471
  • 10
  • 15
  • this question is from 2010 please seek modern solutions – JavaSheriff Apr 14 '20 at 14:23
  • 1
    I would love to find modern solutions but alas I am not capable. Finally I had to step down to the `@where` and `@NamedNativeQueries` solutions mentioned by myself. But you are perfectly right that this is not ideal. I am open to proposals :-) – Björn Nov 20 '20 at 20:36