Hibernate:在单个查询中使用AND与OR结合使用

时间:2015-06-29 12:03:50

标签: java spring hibernate postgresql spring-mvc

我正在开发一个Spring-MVC项目,我需要使用给定的参数搜索一些信息。这是我当前的HQL查询,很可能不会得到我需要的数据。 :

 org.hibernate.Query query = session.createQuery("From GroupNotes as " +
                "n where n.ownednotes.msectionid=:msectionid and n.noteDisabled=false and n.noteInActive=false order by n.mnoteorder");
        query.setParameter("msectionid", msectionid);

    Query hiddenNotesQuery = session.createQuery("from GroupNotes as gn where gn.ownednotes.msectionid=:msectionid and gn.privateNoteUser=:username");
        hiddenNotesQuery.setParameter("msectionid", msectionid);
        hiddenNotesQuery.setParameter("username",person.getUsername());

        List<GroupNotes> groupNotesList = new ArrayList<>();

        groupNotesList.addAll(query.list());
        groupNotesList.addAll(hiddenNotesQuery.list());

我想要这样的事情:

from GroupNotes as n where (n.ownednotes.msectionid=:msectionid and n.noteDisabled=false and n.noteInActive=false and n.privateNoteUser=:"") or (n.ownednotes.msectionid=:msectionid and n.privateNoteUser=:username n.noteDisabled=false and n.noteInActive=false) 

我希望我正在寻找的查询是有意义的,所以基本上它应该检索未禁用且不活动的GroupNotes,但它应该注意它只检索特定用户的Private GroupNotes,因此第一个bracker有privateNoteUser为&#34;&#34;。我不知道我应该在那里拥有什么。

如果有任何疑问,请告诉我。我该如何形成这个查询。

更新:

@Override
    public List<GroupNotes> listGroupNotesBySectionId(int msectionid) {
        Person person = this.personService.getCurrentlyAuthenticatedUser();
        Session session = this.sessionFactory.getCurrentSession();
        org.hibernate.Query query = session.createQuery("From GroupNotes as " +
                "n where n.ownednotes.msectionid=:msectionid and ((n.noteDisabled=false and n.noteInActive=false and n.privateNoteUser=:blank) or (n.privateNoteUser=:username and n.noteDisabled=false and n.noteInActive=false)) order by n.mnoteorder");
        query.setParameter("msectionid", msectionid);
        query.setParameter("msectionid", msectionid);
        query.setParameter("username",person.getUsername());
        query.setParameter("blank",null);
        List<GroupNotes> groupNoteses = query.list();

}

我创建了这样的查询,但我没有回复数据。

1 个答案:

答案 0 :(得分:1)

from GroupNotes as n where n.ownednotes.msectionid=:msectionid  
and (
 ( n.noteDisabled=false and n.noteInActive=false and n.privateNoteUser=:"") 
   or
 ( n.privateNoteUser=:username n.noteDisabled=false and n.noteInActive=false)
)