需求:查询出刚刚插入(删除/修改)的记录的详细信息
1、xxxMapper接口
public interface EmployeeMapper {
// 添加操作
public int insertEmployee(Employee employee);
// 根据ID查询出一条记录
public Employee queryEmployeeByEmployeeId(Integer employeeId);
}
2、xxxMapper.xml
<mapper namespace="com.mybatis.dao.EmployeeMapper">
// 插入一条记录
// useGeneratedKeys:默认值是true,但是还是建议写上
// keyProperty:将刚刚插入的记录的主键使用传入的Employee对象中的employeeId属性接收
<insert id="insertEmployee" useGeneratedKeys="true" keyProperty="employeeId">
INSERT INTO employee VALUES (null,#{employeeName},#{employeePassword},#{employeeAge},#{departmentId})
</insert>
// 根据employeeId查询Employee对象
<select id="queryEmployeeByEmployeeId" resultType="com.mybatis.entity.Employee">
SELECT EMPLOYEE_ID,EMPLOYEE_NAME,EMPLOYEE_PASSWORD,EMPLOYEE_AGE,DEPARTMENT_ID FROM employee
WHERE EMPLOYEE_ID=#{employeeId}
</select>
</mapper>
3、测试类
@Test
public void test01() throws IOException {
SqlSession session = TestMybatis.openSession();
EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
Employee employee = new Employee();
employee.setEmployeeName("田七");
employee.setEmployeeAge("27");
employee.setEmployeePassword("4456");
employee.setDepartmentId(4);
// 这里返回的是影响的行数
int i = mapper.insertEmployee(employee);
// 根据插入的id,查询出刚刚插入的记录,因为我们将插入的主键封装进了Employee对象的employeeId属性中
Employee e = mapper.queryEmployeeByEmployeeId(employee.getEmployeeId());
System.out.println(e);
}
4、测试结果
Employee{employeeId=9, employeeName='田七', employeePassword='4456', employeeAge='27', departmentId=4}