I am doing mysql queries execution from mybatis3.
I am new to this.
What is the difference between collection and association mapping in mybatis 3?
Specific example below.
SELECT e.empid AS empid,e.empname AS empname,
e.empsalary AS empsalary,p.proname AS proname,p.proid AS proid
FROM projects p,employees e,projectassigns pa
WHERE pa.empid=e.empid AND pa.proid=p.proid;
I need all the details of employee and project.
I have given the result map as follows.
<resultMap id="resultProjects" type="com.pratap.model.ProjAssigns">
<association property="employee" javaType="com.pratap.model.Employee"
resultMap="resultEmployees" />
<association property="project" javaType="com.pratap.model.Project"
resultMap="resultProjects" />
</resultMap>
Can anybody explain the difference taking my example or your own example?
I am confused with this..
Thank you.
I am going to assume that you have a many to many relationship between Projects and Employees, which is why you created a Project Assignment table. This Project Assignment table / object may only have two fields/columns: a mapping of project id to employee id – a classic “bridge table” (aka “join” or “junction” table).
When you map this model to an object graph, you have three options:
In your example you chose the last option.
Association
An association is a single mapping for a “has-one” relationship.
Suppose an Employee can only be assigned to one Project at a time. Some models call this a “has-one” or “belongs to” relationship. If you want to make Employee your “primary” focus in the object graph, then you would map it with an association to his/her Project:
In this case your objects would look like this:
Collection
An collection is a “list” or “set” of associations.
Now model the inverse – we make Project the primary focus. A Project has a “has-many” relationship with Employee, so it will have a list or collection of those, so we use a “collection” mapping:
Now your objects would look like this:
Project Association
To have a Project Association object, you would either need:
The first option is rather complex and messy – you would be trying to do relational mapping with object graphs (hash tables most likely).
I would choose to make one of the entities (Project or Employee) the primary focus and then model it as I showed above. The one case I didn’t cover is if Employee is your primary focus and an Employee can be on multiple projects, then make that a “has-many” relationship using a
collectionrather than theassociationI used above.Final Note: if it would help to see examples of using a “has-one”
associationand a “has-many”collection, see the MyBatis Koans I created: https://github.com/midpeter444/mybatis-koans. Koans 10 and 11 demonstrate this.