如何在Java MyBatis 插入数据库返回主键?
1.通过@Options注解获取自增主键ID
当你向一个主键为自增的数据表中插入字段后想要返回刚插入那一条数据的自增id。
@Options (useGeneratedKeys=true, keyProperty="gid", // 主键 keyColumn="paramGid") // 参数实体中的字段
useGeneratedKeys 设置为"true" 表明要 MyBatis 获取由数据库自动生成的主键。
keyProperty=“git” 指定把获取到的主键值注入到相对应参数实体中 eqCsImgId属性。
keyColumn="paramGid指定数据中自增主键的名称。
@Options返回的自增主键封装到 keyProperty 指定的参数类属性中 直接使用get方法获取即可。
注:@Options只能搭配Insert语句使用。
代码示例:
@Insert("insert into pro_group " + "(person_id,gname,group_position,group_introduce,group_establish_time,establish_personid,ascription_companyid) " + "values " + "(#{personId},#{gname},#{position},#{introduce},now(),#{userId},#{companyId})") @Options(useGeneratedKeys=true,keyProperty="gid") int addGrpou(AddGroupParam param);
2.xml中insert标签获取主键
<insert id="insertMerchant" parameterType="Merchant" useGeneratedKeys="true" keyProperty="id">
useGeneratedKeys设置为 true 时,表示如果插入的表id以自增列为主键,则允许 JDBC 支持自动生成主键,并可将自动生成的主键id返回。
useGeneratedKeys参数只针对 insert 语句生效,默认为 false;
当主键id自增的时候返回这个自增的id给keyProperty指定的实体类中的id这个对应数据库主键的属性。
代码示例:(主键为userId)
<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.xf.mybatis.User"> insert into user(userName,password) values(#{userName},#{password}) </insert>