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

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


利用Mybatis 的 selectKey来获得:



	
		select LAST_INSERT_ID();
	
     insert into department() 
		values(#{departmentId},#{departmentName},#{departmentManagerName},#{companyId});
 


  insert into department() 
   values(#{departmentId},#{departmentName},#{departmentManagerName},#{companyId});

注意: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 employees;
	//...GET SET ...
}

测试:

@Test
public 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());
}


输出成功!

你可能感兴趣的:(spring+mybatis)