• Mybatis实现增、删、改操作时返回主键


    需求:查询出刚刚插入(删除/修改)的记录的详细信息

      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}
    

      

  • 相关阅读:
    winfrom 正则验证
    winfrom api发送消息,实现滚动效果(重绘滚动条用)
    C#程序员开发WinForm必须知道的 Window 消息大全
    C# VS EditorBrowsable特性 控制智能提示
    C# Attribute简介
    Win32窗口鼠标消息
    C# 自定义控件容器,设计时可添加控件
    Linux管线命令
    Linux数据流重定向
    Shell中的变量
  • 原文地址:https://www.cnblogs.com/xiaomaomao/p/13659467.html
Copyright © 2020-2023  润新知