除了鉴别器,显然MyBatis还有一对一,一对多的关联。而多对多的关联可以转变为两个一对多的关联,也十分简单,这里我们将讨论它们的使用。
继续我们上篇的代码,我们先看一下员工的Mapper:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ykzhen2015.csdn.mapper.EmployeeMapper"> <resultMap id="employeeMap" type="com.ykzhen2015.csdn.pojo.Employee"> <id property="id" column="id" /> <result property="empName" column="emp_name" /> <result property="sex" column="sex" /> <association property="employeeCard" column="id" select="com.ykzhen2015.csdn.mapper.EmployeeCardMapper.getEmployeeCardByEmpId" /> <collection property="projectList" column="id" select="com.ykzhen2015.csdn.mapper.ProjectMapper.findProjectByEmpId" /> <discriminator javaType="int" column="sex"> <case value="1" resultMap="maleEmployeeMap" /> <case value="2" resultMap="femaleEmployeeMap" /> </discriminator> </resultMap> <select id="getEmployee" parameterType="int" resultMap="employeeMap"> select id, emp_name as empName, sex from t_employee where id =#{id} </select> <resultMap id="maleEmployeeMap" type="com.ykzhen2015.csdn.pojo.MaleEmployee" extends="employeeMap"> <collection property="prostateList" select="com.ykzhen2015.csdn.mapper.MaleEmployeeMapper.findProstateList" column="id" /> </resultMap> <resultMap id="femaleEmployeeMap" type="com.ykzhen2015.csdn.pojo.FemaleEmployee" extends="employeeMap"> <collection property="uterusList" select="com.ykzhen2015.csdn.mapper.FemaleEmployeeMapper.findUterusList" column="id" /> </resultMap> </mapper>
这里我们主要看到association和collection两个标签。
(1)对于association而言,我们在Employee 定义的时候属性employeeCard 是一个POJO对象。
而对于collection而言,我们在Employee定义的时候属性projectList是一个List列表。
这两个需要我们注意。
(2)其次值得我们注意的是他们之间的关联的SQL语句,都是需要用select属性去定义,这里我给的是全限定路径名称和鉴别器是一致的。
(3)再次我们进行关联的时候,往往需要传递参数,这里的column就是一个参数定义。
1、一对一关联(association)
还是老规矩,看看一对一关联的Mapper
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ykzhen2015.csdn.mapper.EmployeeCardMapper"> <select id="getEmployeeCardByEmpId" parameterType="int" resultType="com.ykzhen2015.csdn.pojo.EmployeeCard"> SELECT id, emp_id as empId, card_no as cardNo FROM t_employee_card WHERE emp_id = #{empId} </select> </mapper>
2、一对多关联(collection)
看代码,上面的论述也比较清晰了,我也不再累赘了。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ykzhen2015.csdn.mapper.ProjectMapper"> <select id="findProjectByEmpId" parameterType="int" resultType="com.ykzhen2015.csdn.pojo.Project"> SELECT a.id, a.proj_name as projName FROM t_project a, t_employee_project b where a.id = b.proj_id and b.emp_id = #{empId} </select> </mapper>