I am trying to persist a a relationship between users and friends with a many to many self join. I am using the following method, but no relation is ever created in the database. The user passed a method parameter is created from user input and only contains an id. It also has a Set of friends with only ids. Here is the code:
public User saveUserFriends(User user) {
Transaction transaction = null;
try {
User retrievedUser = (User) session.get(User.class, user.getId());
transaction = session.beginTransaction();
for(User friend :user.getFriends()){
System.out.println("friend "+friend.getId());
friend = (User) session.get(User.class, friend.getId());
System.out.println("retrieved user id "+user.getId());
retrievedUser.getFriends().add(friend);
session.save(retrievedUser);
transaction.commit();
}
}catch (HibernateException e) {
e.printStackTrace();
} finally {
session.close();
}
return user;
}
My hibernate mapping looks like this:
<hibernate-mapping>
<class name="com.User" table="User">
<id name="id" type="int">
<column name="userId" />
<generator class="native" />
</id>
<set name="friends" table="User_Friend"
inverse="true" lazy="false" cascade="none">
<key column="userId"/>
<many-to-many column="friendId" class="com.User" />
</set>
<set name="users" table="User_Friend"
inverse="true" lazy="false" cascade="none">
<key column="friendId"/>
<many-to-many column="userId" class="com.User" />
</set>
</class>
</hibernate-mapping>
The output is only selects. Why are the relationships not being created?
I’m not a specialist of XML mapping, but both sides of the many-to-many associations are marked as the inverse side (
inverse="true"). So Hibernate doesn’t care about them when persisting the user.