MyBatis获取插入记录的自增长字段值

转自:http://blog.csdn.net/hellostory/article/details/6790248

  • 1.在Mybatis Mapper文件中添加属性“useGeneratedKeys”和“keyProperty”,其中keyProperty是Java对象的属性名!
    <insert id="insert" parameterType="Spares"   
          useGeneratedKeys="true" keyProperty="id">  
          insert into spares(spares_id,spares_name,  
              spares_type_id,spares_spec)  
          values(#{id},#{name},#{typeId},#{spec})  
    </insert>
    
  • 2.Mybatis执行完插入语句后,自动将自增长值赋值给对象Spares的属性id。因此,可通过Spares对应的getter方法获取!
    /** 
    * 新增备件 
    * @author hellostory 
    * @param spares 
    * @return 
    */  
    @RequestMapping(value = "/insert")  
    @ResponseBody  
    public JsonResponse insert(Spares spares) {  
      int count = sparesService.insert(spares);  
      System.out.println("共插入" + count + "条记录!"  
              + "\n刚刚插入记录的主键自增长值为:" + spares.getId());
    

 上一篇
去掉Mybatis Generator生成的一堆Example类 去掉Mybatis Generator生成的一堆Example类
上篇讲了如何使用Mybatis Generator生成代码,但是再生成过程中,往往出现一大堆的Example类,而这些Example中的很多方法我们是不需要用到的,因此在生成之前我们可以添加如下代码: <table schema="g
2019-01-20
下一篇 
关于Mybatis出现:there is no getter for property named 'VARCHAR' in 'class com.xxx.xxxxx 关于Mybatis出现:there is no getter for property named 'VARCHAR' in 'class com.xxx.xxxxx
出现这个问题的时候我也是一脸懵逼,后面百度一下但都不是我出现的情况,下面说一下我的解决方法吧 之前看到是插入的时候语句没有截断加上逗号,后面运行一下项目发现还是出现同样的问题, 解决方案如下: 传入的参数我不小心写成了数据库的字段,所以导致
2019-01-20
  目录