How to get the generated primary key in Mybatis
This article mainly introduces how to obtain the generated primary key in Mybatis, which has certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let Xiaobian take you to understand it together.
How to get the generated primary key
For databases that support primary key self-increment (MySQL)
insert into user( user_name, user_password, create_time) values(#{userName}, #{userPassword} , #{createTime, jdbcType= TIMESTAMP})
ParameterType can be left unwritten, Mybatis can infer the type of data passed in. If you want to access the primary key, the parameterType should be java entity or Map. This data can be inserted through the ava entity or Map to obtain the primary key value. Get Primary Key by getUserId
Database that does not support primary key self-increment (Oracle)
For data such as Oracle, there is no function to provide self-increasing primary keys, but to obtain self-increasing primary keys in a sequential manner.
Tags can be used
SELECT USER_ID.nextval as id from dual insert into user( user_id,user_name, user_password, create_time) values(#{userId},#{userName}, #{userPassword} , #{createTime, jdbcType= TIMESTAMP})
The Oracle-generated primary key value is assigned to the userId variable. This userId is the attribute of the USER object, so that the generated primary key value can be returned. If it is only used in insert statements but does not return, keyProperty="any custom variable name", resultType may not be written.
Values in Oracle databases are set to BEFORE because Oracle needs to get values from sequences and insert them into the database as primary keys.
Thank you for reading this article carefully. I hope that the article "How to Get the Generated Primary Key in Mybatis" shared by Xiaobian will be helpful to everyone. At the same time, I hope that everyone will support you a lot and pay attention to the industry information channel. More relevant knowledge is waiting for you to learn!