Hibernate many-to-many data retrieval, via query

前端 未结 2 815
误落风尘
误落风尘 2021-01-24 00:49

Please help me, I think there is something that I am not doing correct. I have User and Contact, that are in Many-to-Many relation.

<
2条回答
  •  借酒劲吻你
    2021-01-24 01:51

    Let's see if I understood right. You want to "get the Contacts associated with the User that is logged in." "I need to check on the Contact status...", correct?

    If that is the case, try writing the query the other way around. So, you can start with the same query you have here . Let's suppose you want "All contacts with status 'ACTIVE' for the User that is logged in".

    // First, retrieve the user you want.
    User user = (User) session.get(User.class, user_id_you_want);
    // Return only the conctats with status 'ACTIVE' 
    List result = new ArrayList();
    for(Contact c : contacts){
      if(c.getStatus().equals("ACTIVE")){
        result.add(c);
      }
    }
    return result;
    

    I hope it helps...

    ===UPDATE1===

    You are right, I thought a user would have a few contacts. How about if you try something like:

    "FROM com.smallworks.model.User as u LEFT JOIN u.contacts as c WHERE u.userId=:userId AND c.status=:status"
    

    Note that you may start your statement with "FROM" instead of "SELECT". See some good examples in this tutorial.

    Another important reference: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html

    Additionally, note that in your case the class User owns the relationship, some statements need to take the ownership in consideration.

提交回复
热议问题