Mybatis sets the auto increment of the primary key, and an error is reported: no setter found for the keyproperty
SQL statement in XML:
<insert id="registerReader" parameterType="com.by.tsgl.bean.Reader" useGeneratedKeys="true" keyProperty="reader_id">
insert into reader(deposit_num,borrowing_num,reader_state,grade_id,user_id)
values(0,0,"normal",1,#{user_id});
</insert>
Test Times Error
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.ExecutorException: Error getting generated key or setting result to parameter object. Cause: org.apache.ibatis.executor.ExecutorException: No setter found for the keyProperty 'reader_id' in 'java.lang.String'.
Solution:
Remove the keyProperty property from the insert tag
Change it to.
<insert id="registerReader" parameterType="com.by.tsgl.bean.Reader" useGeneratedKeys="true">
Cause analysis
The corresponding value in keyProperty is a property of the entity class, not a database field.
The fields that have been set up for primary key auto-increment in the database only need to configure the useGeneratedKeys attribute.
useGeneratedKeys=“true” keyProperty=“id”
When useGeneratedKeys is set to true, it means that if the inserted table id has an auto-incrementing column as the primary key, JDBC is allowed to support automatic primary key generation.
keyProperty=“id”
The automatically generated primary key id can be returned to the id of the passed in object . Since the object we passed in does not have the id field, it naturally does not have its set method, so an error will be reported.
What if there is no primary key in the inserted table?
Can use attributeskeyColumn
<insert id="registerReader" parameterType="com.by.tsgl.bean.Reader" useGeneratedKeys=true keyProperty="userId" keyColumn="user_id">
This annotation means to use the primary key automatically increased by the database and user from the table_ In the ID field, put the data into the member variable userid of the incoming object. If we have specified the primary key in the database table, the keycolumn attribute can be defaulted</ ol>
The following is from the mybatis document
usegeneratedkeys
(only applicable to insert and update) this will make mybatis use JDBC’s getgeneratedkeys
method to retrieve the primary key generated internally by the database (such as the auto increment field of relational database management systems such as MySQL and SQL Server). The default value is false
keyproperty
(only applicable to insert and update) specifies the property that can uniquely identify the object. Mybatis will use the return value of getgeneratedkeys
or the selectkey sub element of the insert statement to set its value. The default value is unset. If more than one column is generated, multiple attribute names can be separated by commas.