Mybatis generator MySQL auto-increment ID has duplicate problems
PS: Sometimes not paying attention may lead to this problem. Only records are taken here for reference.
Code description:
The database is MySQL, and the code generated by generator is increased by itself. The ID is used to obtain it using selectKey.
Problem description
When insert, when adding, the first data is added successfully, and then when adding the second data, it will prompt failure. The reason for the failure is the ID or the previous ID value used. The repetition of the primary key causes the insertion to fail.
The exception is as follows:
Caused by: .: Duplicate entry '4' for key 'PRIMARY'
Cause of the problem
BEFORE or AFTER
<selectKey keyProperty="id" order="BEFORE" resultType=""> SELECT LAST_INSERT_ID() </selectKey>
It should be noted that
Oracle uses before, MySQL uses after
When generating code, you can use identity="true" to specify whether the generated selectKey is before or after
<generatedKey column="id" sqlStatement="Mysql" identity="true" />
Note:
The problem does not exist when using useGeneratedKeys="true" keyProperty="id".
Repeat when mybatis generator generates an entity
When generating mysql database entity in Java project, since there are multiple libraries in the mysql database, if duplicate tables appear in the library, the generated entity code will have duplicate problems. The reason is that all libraries will be scanned when the database generates entities.
Solution
1. The first type
jdbc:mysql://localhost:3306/table?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&nullCatalogMeansCurrent=true
Just add nullCatalogMeansCurrent=true to the connection string
2. The second method is to set up
<table tableName="table" catalog="dataName"></table>
Specify library name using catalog
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.