title: Saving/Updating collections with mybatis, what is the common practice?
body: <p>I've decided to try and use mybatis for a new project. I'm decently familiar with SQL, and I've had some bad experiences with hibernate recently so I'm looking for a more low-level approach to DAO.</p>
  
  <p>Seems to be quite nice except for one thing, and that is handling collections.</p>
  
  <p>I have two POJOs, group and user, that are many-to-many. I've decided on a design philosophy that a POJO that has a collection should only update the M-M relation between the tables when saved. So, for example, when I save a group object that has a collection of users, the design philosophy dictates that the users should already be saved, and I only have to save the group and the group_user relation in the database.</p>
  
  <p>so, for the saveGroup function in the interface, I've made this XML mapping for mybatis:</p>
  
  <pre><code>    &lt;insert id="saveGroup" keyColumn="id"
      parameterType="se.myapp.domain.Group"&gt;
      &lt;choose&gt;
          &lt;when test="id == null"&gt;
          INSERT INTO myapp_group (name, description)
          VALUES
          (#{username}, #{password});
          &lt;/when&gt;
          &lt;otherwise&gt;
          UPDATE myapp_group set name=#{name}, description=#{description}
          where id=#{id};
          &lt;/otherwise&gt;
      &lt;/choose&gt;
  
      &lt;if test="users != null"&gt;
          create temporary table tmpnewgroups (group_id integer, user_id integer);
  
          insert into tmpnewgroups (group_id, user_id) values (
          &lt;foreach collection="users" item="user" open="" close="" separator="),()"&gt;
               #{id},#{user.id}
          &lt;/foreach&gt;
          );
  
          insert into myapp_user_group(group_id, user_id) 
          select tmp.group_id, tmp.user_id 
          from tmpnewgroups tmp 
          left outer join myapp_user_group ug 
              on ug.group_id = tmp.group_id and ug.user_id = tmp.user_id
          where ug.group_id is null;
  
          delete from myapp_user_group 
          where group_id = #{id} and user_id not in (select user_id from tmpnewgroups);
      &lt;/if&gt;
  
  &lt;/insert&gt;
  </code></pre>
  
  <p>This does work as intended (insert/updates the group, saves the collection of users as relations in the database). But I don't really feel that this is best practice. The application is made so that I can switch to hibernate if needed, so the logic for saving collection preferably should be in the database layer. Is there some "magic" in mybatis that I'm not aware of that could streamline operations like this?</p>
  
  <p>Any thoughts on how to improve this? Or should I rethink the application design and put the handling of collections further up in the model?</p>