开发者

Ignore Hibernate @Where annotation

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

public class EntityA {

    @OneToMany
    @Where(...)
    private List<开发者_如何学C;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?


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).


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.


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();


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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜