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.
In the XML mapping Contact, the mapping of userSet is completely wrong:
<hibernate-mapping package="com.smallworks.model" schema="projectdb">
<class name="Contact" table="CONTACT">
<!-- ... --->
<set inverse="true" lazy="false" name="userSet" sort="unsorted" table="USER_CONTACT">
<key column="USER_ID"/>
<many-to-many class="com.smallworks.model.Contact" column="CONTACT_ID" unique="false"/>
</set>
</class>
</hibernate-mapping>
It should be:
<set inverse="true" lazy="false" name="userSet" sort="unsorted" table="USER_CONTACT">
<key column="CONTACT_ID"/>
<many-to-many class="com.smallworks.model.User" column="USER_ID" unique="false"/>
</set>
It looks to me like you copy-and-pasted this from User and then didn't update it.
Why are you using XML rather than annotations? XML is much more error-prone, as you can see. In addition, a lot of these settings should be defaulted correctly by Hibernate. If you had just left out some of these attributes, it probably would have worked fine.
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.