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.
Seems to be quite nice except for one thing, and that is handling collections.
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.
so, for the saveGroup function in the interface, I've made this XML mapping for mybatis:
<insert id="saveGroup" keyColumn="id"
parameterType="se.myapp.domain.Group">
<choose>
<when test="id == null">
INSERT INTO myapp_group (name, description)
VALUES
(#{username}, #{password});
</when>
<otherwise>
UPDATE myapp_group set name=#{name}, description=#{description}
where id=#{id};
</otherwise>
</choose>
<if test="users != null">
create temporary table tmpnewgroups (group_id integer, user_id integer);
insert into tmpnewgroups (group_id, user_id) values (
<foreach collection="users" item="user" open="" close="" separator="),()">
#{id},#{user.id}
</foreach>
);
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);
</if>
</insert>
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?
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?