mybatis 06 对多关联
2016-10-17 本文已影响9人
小小机器人
概念:
一个部门对应多个员工
部门表中有List员工属性
案例:
配置文件
myBatis-conf.xml
<!--别名-->
<typeAliases>
<typeAlias type="com.xxjqr.relation02.Emp" alias="Emp"/>
<typeAlias type="com.xxjqr.relation02.Dept" alias="Dept"/>
</typeAliases>
<!---关联配置文件-->
<mappers>
<mapper resource="com/xxjqr/relation02/empMapper.xml"/>
<mapper resource="com/xxjqr/relation02/deptMapper.xml"/>
</mappers>
deptMapper.xml
<?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.xxjqr.relation02.deptMapper">
<resultMap type="Dept" id="deptResultMap">
<id column="dept_id" property="deptId"/>
<result column="dept_name" property="deptName"/>
<result column="dept_address" property="deptAddress"/>
<!--collection用来配置对多的关联 -->
<collection property="emps" resultMap="com.xxjqr.relation02.empMapper.empResultMap"></collection>
</resultMap>
<!-- 根据部门名称查询部门信息(包括部门员工信息) -->
<select id="selectDeptEmpList" parameterType="string" resultMap="deptResultMap">
select e.*,d.* from emp_t e inner join dept_t d on e.dept_id = d.dept_id
where d.dept_name = #{deptName}
</select>
</mapper>
empMapper.xml
<?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.xxjqr.relation02.empMapper">
<resultMap type="Emp" id="empResultMap">
<id column="emp_id" property="empId"/>
<result column="emp_name" property="empName"/>
<result column="emp_sex" property="empSex"/>
</resultMap>
</mapper>
类
@Data
public class Dept {
private int deptId;
private String deptName;
private String deptAddress;
private List<Emp> emps;
}
@Data
public class Emp {
private String empId;
private String empName;
private String empSex;
}
public class UserDao {
public List<Dept> selectList (String name){
List<Dept> depts = null;
SqlSession session = null;
try {
session = MybatisSessionFactory.getSession();
depts = session.selectList("com.xxjqr.relation02.deptMapper.selectDeptEmpList",name);
session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
MybatisSessionFactory.closeSession();
} catch (Exception e) {
e.printStackTrace();
}
}
return depts;
}
}
public class TestUserDao {
private UserDao userDao = new UserDao();
@Test
public void test(){
List<Dept> depts = null;
depts = userDao.selectList("开发部");
System.out.println(depts);
}
}
MybatisSessionFactory