添加数据返回主键ID
作者:张业明
添加序列
create sequence seq_stu_id
与普通添加语句不同的是在insert里添加selectKey 标签。插入数据后,返回自动增长列的ID值,将sql语句返回值赋给parameterType绑定对象的Id值。
<insert id="addStudentAndReturnID" parameterType="Student">
insert into student(stu_id,stu_name,stu_address) values(seq_stu_id.nextval,#{stu_name},#{stu_address})
<selectKey keyProperty="stu_id" order="AFTER" resultType="Integer">
select seq_stu_id.currval from dual
</selectKey>
</insert>
编写测试方法:
public static Integer addStudentAndReturnID(Student stu)
{
SqlSession sqlSession=MybatisUtils.getSqlSession();
try {
sqlSession.insert("stu.addStudentAndReturnID", stu);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}finally
{
//释放资源 必须执行
if(sqlSession!=null)
{
sqlSession.close();//connection.close();
}
}
return stu.getStu_id();
}
public static void main(String[] args) {
Student stu=new Student(null, "madonghao", "lanyuelu");
addStudent(stu);
Integer id=addStudentAndReturnID(stu);
System.out.println("id:"+id);
}