一、在已经通过逆向工程生成相应类、接口、mapper后,希望向类中注入属性并添加自己的方法
(1)向类中注入属性: private Department department;
向员工类中注入部门的属性,并生成get、set方法
(2)修改mapper接口,添加新的方法:
List<Employee> selectByExampleWithDept(EmployeeExample example);
Employee selectByPrimaryKeyWithDept(Integer empId);
(3)修改配置文件
<resultMap type="com.atguigu.crud.bean.Employee" id="WithDeptResultMap">
<id column="emp_id" jdbcType="INTEGER" property="empId" />
<result column="emp_name" jdbcType="VARCHAR" property="empName" />
<result column="gender" jdbcType="CHAR" property="gender" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="d_id" jdbcType="INTEGER" property="dId" />
<!-- 指定联合查询出的部门字段的封装 -->
<association property="department" javaType="com.atguigu.crud.bean.Department">
<id column="dept_id" property="deptId"/>
<result column="dept_name" property="deptName"/>
</association>
</resultMap>
<sql id="WithDept_Column_List">
e.emp_id, e.emp_name, e.gender, e.email, e.d_id,d.dept_id,d.dept_name
</sql>
<!-- List<Employee> selectByExampleWithDept(EmployeeExample example);
Employee selectByPrimaryKeyWithDept(Integer empId);
-->
<!-- 查询员工同时带部门信息 -->
<select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="WithDept_Column_List" />
FROM tbl_emp e
left join tbl_dept d on e.`d_id`=d.`dept_id`
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">
select
<include refid="WithDept_Column_List" />
FROM tbl_emp e
left join tbl_dept d on e.`d_id`=d.`dept_id`
where emp_id = #{empId,jdbcType=INTEGER}
</select>
二、使用Spring的单元测试
推荐Spring的项目就可以使用Spring的单元测试,可以自动注入我们需要的组件
* 1.导入Spring Test模块
* 2.@ContextConfiguration指定配置文件的位置
* 3.@RunWith(SpringJUnit4ClassRunner.class)
* 4.直接@Autowired要使用的组件即可
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring/applicationContext-*.xml"})
public class MapperTest {
@Autowired
DepartmentMapper departmentMapper;
/**
* 测试DepartmentMapper
*
*/
@Test
public void testCRUD(){
System.out.println(departmentMapper);
}
}
控制台出现以下情况说明测试成功,或者单元测试结果显示绿色条