I have never been able to figure out an efficient way to deal with updates to a collection. As an example, I have a user that has a set of emails. USERS is a database table itself containing a username and password. There is another database table EMAILS that contains an email address and a foreign key USER_ID referencing the primary key of the USERS table. In the java code, the Users class is able to update the java.util.Set containing it's email addresses. Let's say that I update an email address in the Set and delete another for a certain user and then I update the java.util.Set in the Users class with the up to date email addresses for that user. When I update the user to the database using hibernate, using
Code:
session.update(user);
The set does not automatically get updated so I need to do the following:
Code:
Query query = session.createQuery("delete from Emails where user = :user");
query.setParameter("user", user);
query.executeUpdate();
Set<Emails> emails = user.getEmails();
if (emails != null)
{
for (Emails email : emails)
{
session.save(email);
}
}
So basically, I need to delete all the email associated with the user and then need to add the newly updated emails back into the database. This is a really bad way of updating the emails but this is the only way that I could get the update to work in hibernate. Since, the java.util.Set of email addresses were already updated in a previous Java class I really don't know which email addresses were updated, so I just clean out all my previous email addresses and just insert all the email addresses in the Set. How do I update the collection in the most efficient way? I sure that I am not the only person that has faced the situation and hope that someone can shed some light on how I can improve this.
Thanks in advanced!
Code:
<hibernate-mapping>
<class lazy="false" name="test.User" table="users" catalog="staff">
<id name="id" type="int">
<column name="id" />
<generator class="identity"></generator>
</id>
<property name="username" type="string">
<column name="username" not-null="true">
<comment></comment>
</column>
</property>
<property name="password" type="string">
<column name="password" not-null="true">
<comment></comment>
</column>
</property>
<set lazy="extra" name="emails" inverse="true">
<key>
<column name="user_id" not-null="true">
<comment></comment>
</column>
</key>
<one-to-many class="test.Emails" />
</set>
</class>
</hibernate-mapping>
Code: