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!");
 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值