mybatis 添加一条新数据并返回此数据的ID(主键)

来源:互联网 发布:break c语言定义 编辑:程序博客网 时间:2024/05/06 00:22

通常数据库中表的主键是‘自动递增(mysql)’或’序列(oracle)‘,但插入数据后又要取得些条数据的ID(将ID做为主键)


利用Mybatis 的 selectKey来获得:

<!-- 添加部门 返回部门ID --><insert id="addDept" parameterType="com.demo.model.Department" keyProperty="id"><selectKey keyProperty='id' resultType='int' order='AFTER'  >select LAST_INSERT_ID();</selectKey>     insert into department(<include refid="departmentAllField"/>) values(#{departmentId},#{departmentName},#{departmentManagerName},#{companyId}); </insert>

<insert id="addDept" parameterType="com.demo.model.Department" useGeneratedKeys="true" keyProperty="id">  insert into department(<include refid="departmentAllField"/>)    values(#{departmentId},#{departmentName},#{departmentManagerName},#{companyId});</insert><span style="font-family: Arial, Helvetica, sans-serif;"></span>

注意:insert 标签中的 keyProperty  和  selectKey标签块中的 LAET_INSERT_ID() ,另外 order属性 对于 oracl为 BEFORE; mysql为AFTER


实体类:

public class Department {private int id;private int departmentId;private String departmentName;private String departmentManagerName;private int companyId;private List<Employee> employees;//...GET SET ...}

测试:

@Testpublic void testDao(){deptDao = session.getMapper(DepartmentDao.class);Department department = new Department();department.setDepartmentName("ares");department.setDepartmentManagerName("tom");department.setDepartmentId(32);department.setCompanyId(6201);deptDao.addDept(department);System.out.println("新部门ID:"+department.getId());}


输出成功!

0 0
原创粉丝点击