MyBatis 插入主键方式和返回主键】的更多相关文章

这使用的mysql数据库,下面这种方式(没有给mysql设置自动增长)是插入主键方式: <insert id="insertBook" parameterType="com.test.entity.Book"> <selectKey keyProperty="id" resultType="int" order="BEFORE"> select max(id)+1 from book…
需求:使用批量插入后,需要insert之后的每一条记录的ID 注意:Mybatis3.3.1的版本以后支持批量插入后返回主键ID 示例: domin.java: public class User { private int d; private String name; private String pwd; public long getId() { return id; } public void setId(long id) { this.id = id; } public String…
在使用MyBatis做持久层时,insert语句默认是不返回记录的主键值,而是返回插入的记录条数:如果业务层需要得到记录的主键时,可以通过Mapper.XML配置的方式来完成这个功能. 在 INSERT 标签 添加 useGeneratedKeys="true" keyProperty="id" 即可: <insert id="insertFeedback" useGeneratedKeys="true" keyProp…
mapper文件 映射文件中在insert中设置useGeneratedKeys为true,keyProperty设置为主键名称 <insert id="addEmployees" useGeneratedKeys="true" keyProperty="id"> INSERT INTO employees (emp_name, emp_age, emp_no, hire_date, sal, deptno, mgr, user_na…
参考:mybatis添加记录时返回主键id 场景 有些时候我们在添加记录成功后希望能直接获取到该记录的主键id值,而不需要再执行一次查询操作.在使用mybatis作为ORM组件时,可以很方便地达到这个目的.鉴于mybatis目前已经支持xml配置和注解2种方式,所以分别给予详细介绍. 数据表设计: drop table if exists `test`; create table `test` ( `id` ) NOT NULL AUTO_INCREMENT COMMENT 'ID', // 主…
1.项目环境--SpringBoot下的SSM+Maven 2.问题出现位置--Dao层和Mapper文件 错误代码如下图: dao层: mapper文件: 错误代码分析: 使用useGeneratedKeys生成主键时 (1)如果在DAO层使用@Param注解传递参数,则 keyProperty 属性 需要通过 "注解"+"主键id" 的格式,否则无法返回主键. (2)如果在DAO层只有单个参数传递(不需要使用@Param注解穿传递参数),则 keyPropert…
转载至:https://www.liyongzhen.com/ 上一节课里我们学习通过PreparedStatement对象执行带参数的查询SQL和修改SQL. 这节课我们学习使用 PreparedStatement对象执行插入SQL,并且返回主键. 要返回主键,有一个前提,就是数据库表必须有主键自增. 下面的代码演示了执行插入SQL并返回主键的用法. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 String sql = "INSERT INT…
有时候插入记录之后需要使用到插入记录的主键,通常是再查询一次来获取主键,但是MyBatis插入记录时可以设置成返回主键id,简化操作,方法大致有两种. 对应实体类: public class User { private int userId; private String userName; private int userAge; } 对应DAO类: public interface UserMapper { int save(User user); } 方法一.使用useGenerated…
最近在搞一个电商系统中由于业务需求,需要在插入一条产品信息后返回产品Id,刚开始遇到一些坑,这里做下笔记,以防今后忘记. 类似下面这段代码一样获取插入后的主键 User user = new User(); user.setUserName("chenzhou"); user.setPassword("xxxx"); user.setComment("测试插入数据返回主键功能"); System.out.println("插入前主键为:…
mybatis insert返回主键(sqlserver2008)   MyBatisXML配置,下面两种方式都行 方式1: <insert id="insert" parameterType="com.user.model.User" >   <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" …