MyBatis用序列插入对象
映射文件:
?
<insert id="insertStudentBySequence" parameterType="Student">
??<selectKey?resultType="int" keyProperty="s_id"?order="BEFORE">
???select studentPKSequence.nextVal
???from dual
??</selectKey>
??
??insert into student(s_id,s_name,s_age)
??values ??????(#{s_id},#{s_name},#{s_age})
?</insert>
-----------------------
resultType="int" 返回的是一个int类型
keyProperty 把返回值,赋值给:parameterType中对象的对象的属性,也就是Student类中的s_id属性
order属性,在mybatis-3.1.0要加上该属性,表示先执行此步骤
-----------------------
DAO:
?
public void addStudentBySequence(Student stu) {
??SqlSession sqlSession = null;
??try{
???sqlSession = sf.openSession();
???sqlSession.insert("insertStudentBySequence", stu);
???System.out.println("s_id: "+stu.getS_id());
???sqlSession.commit();//这里一定要提交,不然数据进不去数据库中
??}finally{
???sqlSession.close();
??}
?}
?
----------------------------------------------------
测试:
?@Test
?public void addStudentBySequenceTest(){
??IStudentDAO sDAO = new IStudentDAOIbatisImpl();
??Student student = new Student();
??//student.setS_id(500);
??student.setS_age(18);
??student.setS_name("yyy");
??sDAO.addStudentBySequence(student);
??System.out.println("add ok!");
?}
?