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即可