首页 技术 正文
技术 2022年11月21日
0 收藏 772 点赞 2,156 浏览 1414 个字

一、场景:

插入数据库的值需要立即得到返回的主键id进行下一步程序操作

二、解决方法:

第一种:使用通用mapper的插入方法

Mapper.insertSelective(record);

此方法:插入一条数据,只插入不为null的字段,不会影响有默认值的字段
支持Oracle序列,UUID,类似Mysql的INDENTITY自动增长(自动回写)
优先使用传入的参数值,参数值空时,才会使用序列、UUID,自动增长

controller的实际应用:使用方法id会直接将映射到参数的实体上使用时直接使用参数的实体get获取值

通用mapper相关配置查看其它文章   http://blog.csdn.net/isea533/article/details/41457529

第二种:编写sql语句

dao层方法:

  1. /**
  2. * 插入数据库并返回主键id
  3. * @param batch
  4. * @return
  5. */
  6. Integer insertBatchReturnId(Batch batch);

xml的sql语句写法

记得加上useGeneratedKeys和keyProperty配置即可,前者是指设置是否使用jdbc的getGenereatedKeys方法获取主键并赋值到keyProperty设置的属性中,后者即实体类主键字段(并且大小写要对应上)

  1. <insert id=”insertBatchReturnId” useGeneratedKeys=”true” keyProperty=”id” parameterType=”org.uz.dxt.model.bankbase.Batch”  >
  2. insert into t_batch (
  3. batchCode,
  4. bankCode,
  5. bizType,
  6. companyCode,
  7. wtEndDate,
  8. wtDate,
  9. contractId,
  10. totalCount,
  11. totalBase,
  12. handCode)
  13. values
  14. ( #{batchcode},
  15. #{bankcode},
  16. #{biztype},
  17. #{companycode},
  18. #{wtenddate},
  19. #{wtdate},
  20. #{contractid},
  21. #{totalcount},
  22. #{totalbase},
  23. #{handCode})
  24. </insert>

controller的实际应用:使用方法id会直接将映射到参数的实体上使用时直接使用参数的实体get获取值

  1. batchService.insertBatch(param);//实体
  2. idlist.add(param.getId());

第三种:sql语句使用<selectKey>获取自增逐渐id

  1. <insert id=”add” parameterType=”EStudent”>
  2. // 下面是SQLServer获取最近一次插入记录的主键值的方式
  3. <selectKey resultType=”_long” keyProperty=”id” order=”AFTER”>
  4. select @@IDENTITY as id
  5. </selectKey>
  6. insert into TStudent(name, age) values(#{name}, #{age})
  7. </insert>

使用用法同上

这里推荐使用第一种和第二种中方法

第三种方法对oracl额外的配置

controller的实际应用:使用方法id会直接将映射到参数的实体上使用时直接使用参数的实体get获取值

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,954
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,479
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,291
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,108
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,740
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,774