MyBatis 获取插入数据后的自增 ID 值
在<insert>标签中设置和,MyBatis 会自动将自增 ID 赋值给传入参数对象的对应属性。
·
1.说明
在<insert>
标签中设置useGeneratedKeys="true"
和keyProperty="id"
,MyBatis 会自动将自增 ID 赋值给传入参数对象的对应属性。
2.案例说明
2.1.数据传输层
RpCompanyconfigMapper.xml,设置useGeneratedKeys="true" keyProperty="companyId"
<insert id="insertRpCompanyconfig" parameterType="RpCompanyconfig" useGeneratedKeys="true" keyProperty="companyId">
insert into rp_companyconfig
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="companyName != null">company_name,</if>
<if test="companyCode != null">company_code,</if>
<if test="createBy != null">create_by,</if>
<if test="createTime != null">create_time,</if>
<if test="updateBy != null">update_by,</if>
<if test="updateTime != null">update_time,</if>
<if test="remark != null">remark,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="companyName != null">#{companyName},</if>
<if test="companyCode != null">#{companyCode},</if>
<if test="createBy != null">#{createBy},</if>
<if test="createTime != null">#{createTime},</if>
<if test="updateBy != null">#{updateBy},</if>
<if test="updateTime != null">#{updateTime},</if>
<if test="remark != null">#{remark},</if>
</trim>
</insert>
2.2 数据访问层类
public interface RpCompanyconfigMapper
public int insertRpCompanyconfig(RpCompanyconfig rpCompanyconfig);
2.3.服务层接口类
public interface IRpCompanyconfigService
public int insertRpCompanyconfig(RpCompanyconfig rpCompanyconfig);
2.4.服务层实现类
@Service
public class RpCompanyconfigServiceImpl implements IRpCompanyconfigService
*/
@Override
public int insertRpCompanyconfig(RpCompanyconfig rpCompanyconfig)
{
rpCompanyconfig.setCreateTime(DateUtils.getNowDate());
int ttt=rpCompanyconfigMapper.insertRpCompanyconfig(rpCompanyconfig);
return ttt;
}
3.效果,查看companyId
4.扩展
方法二:使用 selectKey 标签(适用于不支持自动返回主键的数据库)
对于不支持自动返回主键的数据库(如 Oracle),可以使用<selectKey>
标签获取自增 ID。
xml
<insert id="insertUser" parameterType="User">
<selectKey keyProperty="id" resultType="long" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO user (username, email)
VALUES (#{username}, #{email})
</insert>
order="AFTER"
表示在 INSERT 语句执行后执行 SELECT LAST_INSERT_ID ()。
方法三:通过注解方式(Java 注解配置)
如果你使用 Java 注解而非 XML 配置,可以这样写:
@Insert("INSERT INTO user (username, email) VALUES (#{username}, #{email})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertUser(User user);
使用 @Options 注解设置 useGeneratedKeys 和 keyProperty 属性。
注意事项
- keyProperty:指定实体类中对应的主键属性名。
- resultType:指定返回主键的类型。
- order 属性:
AFTER
:适用于 MySQL 等支持自动生成主键的数据库。BEFORE
:适用于 Oracle 等需要先获取序列值的数据库。

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)