在MyBatis中,当执行插入操作并希望返回生成的主键ID时,可以通过配置useGeneratedKeys和keyProperty属性来实现。以下是实现这一功能的详细步骤: 1. 编写MyBatis的insert语句 首先,在MyBatis的映射文件(通常是XML文件)中编写插入语句。以下是一个示例: xml <insert id="insertUser" parameterType="User"> insert ...
在 insert 元素结束后,我们可以使用 SELECT LAST_INSERT_ID() 函数获取插入记录的主键 ID:<insert id="insertUser" parameterType="User" useGeneratedKeys="false"> insert into user (name, age) values (#{name}, #{age}) <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER">...
添加批量记录时返回主键ID 如果希望执行批量添加并返回各记录主键字段值,只能在xml映射器中实现,在接口映射器中无法做到。 代码语言:javascript 复制 <!--批量添加数据,并返回主键字段--><insert id="insert"useGeneratedKeys="true"keyProperty="id">insert intostu(name,age)values<foreach collection="list"separato...
<insertid="insertStudent"parameterType="Student">insert into student(name, age) VALUES (#{name} , #{age})<selectKeykeyProperty="sid"order="AFTER"resultType="int">SELECT LAST_INSERT_ID()</selectKey></insert> 说明: 1、< insert> 标签中没有 resultType 属性,但是 < selectKey> 标签是有的。 2...
MyBatis插入数据的时候,返回该记录的id<insert id="insert" keyProperty="id" useGeneratedKeys="true" parameterType="com.demo.domain.CountRateConfig"> insert into query_rate_config (code,partner_type,search_count, booking_count, ticket_count,rate_type) values (#{code,jdbcType=VARCHAR},#...
id"> INSERT INTO users (username, password) VALUES (#{username}, #{password}) </insert>...
二、一般的INSERT操作——返回值为插入的记录数目 mapper接口代码: /** * 添加学生信息 * @param student 学生实例 * @return 成功操作的记录数目 */ int add(EStudent student); mapper.xml: <insert id="add" parameterType="EStudent"> insert into TStudent(name, age) values(#{name}, #{age}) ...
对于批量插入同时返回主键值,MySQL可以利用LAST_INSERT_ID()函数在每条插入后立即获取自增ID(但一次只能获取一条),因此对于批量插入,可能需要进行多次单独的插入并逐次获取主键,或者利用数据库特定的扩展功能(如MySQL的GET_LOCK()与RELEASE_LOCK()配合多行插入)来确保正确获取每个插入行的自增ID。
我们知道JDBC可以实现插入语句后返回主键Id,那mybatis可以实现吗?答案是肯定的。 1、MySQL数据库设置ID自增情况 <insertid="insertUser"parameterType="com.crush.mybatisplus.entity.User"> INSERTINTOtb_user(username,password)VALUES(#{username},#{password}); ...
1<insertid="save"useGeneratedKeys="true"keyProperty="userId"keyColumn="id">2INSERT INTO user (id, name, age)3VALUES (UUID(), #{userName}, #{userAge})4</insert> 该方法只支持主键非自增的情况。只需要在插入的方法标签上,添加useGeneratedKeys、keyProperty、keyColumn三个属性。