useGeneratedKeys=“true“ keyProperty=“id“ 插入数据后返回主键

Mybatis 配置文件 useGeneratedKeys 参数只针对 insert 语句生效,默认为 false。当设置为 true 时,表示如果插入的表以自增列为主键,则允许 JDBC 支持自动生成主键,并可将自动生成的主键返回。
useGeneratedKeys =true 这个表示插入数据之后返回一个自增的主键id给你对应实体类中的主键属性。通过这个设置可以解决在主键自增的情况下通过实体的getter方法获取主键(当然还需要keyproperty指明数据库中返回的主键id给实体类中的哪个属性)。
keyproperty=主键,这样就可以解决在主键自增的情况下获取主键。

<insert id="insertReportschedule" useGeneratedKeys="true" keyProperty="id">
        <selectKey keyProperty="id" keyColumn="ID" resultType="java.lang.Integer" order="BEFORE">
            select NULLIF(max(id),0)+1 from product_systeam.reportschedule
        </selectKey>
        insert into product_systeam.reportschedule
        (
        <trim suffixOverrides=",">
            <if test="id != null and id != ''">
                ID,
            </if>
            <if test="reportID != null and reportID != ''">
                ReportID,
            </if>
            <if test="reportPeople != null and reportPeople != ''">
                ReportPeople,
            </if>
            <if test="beforeReportSchedule != null and beforeReportSchedule != ''">
                BeforeReportSchedule,
            </if>
        </trim>
        )
        VALUES (
        <trim suffixOverrides=",">
            <if test="id != null and id != ''">
                #{id},
            </if>
            <if test="reportID != null and reportID != ''">
                #{reportID},
            </if>
            <if test="reportPeople != null and reportPeople != ''">
                #{reportPeople},
            </if>
            <if test="beforeReportSchedule != null and beforeReportSchedule != ''">
                #{beforeReportSchedule},
            </if>
        </trim>
        )
    </insert>

这时数据会返回到原先的实体类中。

reportschedule.getId()

查看实体类的id即可

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值