挿入操作後、主キー ID がすぐに返されます。多くの情報を参照し、keyProperty 属性と useGeneratedKeys 属性を使用しました。useGeneratedKeys パラメーターは挿入ステートメントに対してのみ有効で、デフォルトは false です。true に設定すると、挿入されたテーブルに主キーとして自動インクリメント列がある場合、JDBC で主キーの自動生成のサポートが許可され、自動生成された主キーを返すことができることを意味します。
主に次のような方法で行われます。
<insert id="insertFileRecord" useGeneratedKeys="true" keyProperty="id">
insert xxx
</insert>
しかし、それは効果がなかったので、useGeneratedKeys="true" を使用する方法を探したところ、記述が少なくなったことがわかりました。
<insert id="insertFileRecord" parameterType="FileRecord" useGeneratedKeys="true" keyProperty="id">
insert xxx
</insert>
parameterType は、Mybatis Mapper ファイルの属性「useGeneratedKeys」と「keyProperty」をどのエンティティ クラスに追加するかを指示することしかできません。ここで、keyProperty は、テーブルのフィールド名ではなく、Java オブジェクトの属性名です。
しかし、それでもうまくいかなかったので、自動インクリメントされる ID が long 型であるのではないかと疑い始めましたが、実際はそうではなく、マッパー インターフェイス クラスにそのようなアノテーションを追加しました。
int insertFileRecord(@Param("fileRecord") FileRecord fileRecord);
そして、挿入ステートメント fileRecord.fileName で @Param を削除し、最後に ID を確認します。
最後に、完全な文章を添付します。
マッパーインターフェイス:
/**
* @Description: 新增数据
* @Author: wj
* @param: cc.jz.work.entity.FileRecord
* @Return: 影响行数
* @Date: 2022-03-31 10:37:18
*/
int insertFileRecord(FileRecord fileRecord);
XML:
<insert id="insertFileRecord" parameterType="cc.jz.work.entity.FileRecord" useGeneratedKeys="true" keyProperty="id">
insert into
file_record
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="fileAddress != null and fileAddress != ''">
file_address,
</if>
<if test="fileName != null and fileName != ''">
file_name,
</if>
<if test="uploadUserId != null">
upload_user_id,
</if>
<if test="uploadTime != null">
upload_time,
</if>
<if test="status != null and status != ''">
status,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="fileAddress != null and fileAddress != ''">
#{fileAddress,jdbcType=VARCHAR},
</if>
<if test="fileName != null and fileName != ''">
#{fileName,jdbcType=VARCHAR},
</if>
<if test="uploadUserId != null">
#{uploadUserId,jdbcType=INTEGER},
</if>
<if test="uploadTime != null">
#{uploadTime,jdbcType=TIMESTAMP},
</if>
<if test="status != null and status != ''">
#{status,jdbcType=VARCHAR},
</if>
</trim>
</insert>