Note:
This topic has been translated from a Chinese forum by GPT and might contain errors.
Original topic: tidb auto_random返回刚插入的主键id为0
[TiDB Usage Environment] Production Environment / Testing / PoC
[TiDB Version]
V6.5.9
[Reproduction Path] What operations were performed when the issue occurred
- Create a table with the primary key id as auto_random random primary key
- Insert multiple rows, the ids returned by mybatis for the newly inserted rows are all 0 mysql如何获取刚插入的主键id_mysql 插入获取id-CSDN博客
- Seeking help, for random primary keys, batch insert multiple rows, is there a way to avoid the primary key id being 0?
[Encountered Issue: Issue Phenomenon and Impact]
[Resource Configuration] Go to TiDB Dashboard - Cluster Info - Hosts and take a screenshot of this page
[Attachments: Screenshots / Logs / Monitoring]
This is usually because MyBatis does not handle the special behavior of TiDB’s LAST_INSERT_ID()
function by default. In the MyBatis mapping file, make sure you have correctly configured how to retrieve the generated ID. For example, you may need to configure the useGeneratedKeys="true"
and keyProperty="id"
attributes so that MyBatis can capture and return the database-generated ID.
Not all returns are 0, occasionally there are occurrences.
Write a test method to test it, print out all the logs, and see what logs are output when it returns 0.
Based on the above configuration, it can return now, but it only returns LAST_INSERT_ID. It’s batch processing, inserting multiple rows. How can it return all of them?
Is it feasible to first retrieve and then write?
According to the method mentioned above, first fetch, if the fetch returns 0, fetch again, then write. Adjust the business code accordingly.