The way mysql insert data in MyBatis and return auto-increment primary key and non-auto-increment primary key

The way mysql insert data in MyBatis and return auto-increment primary key and non-auto-increment primary key

The insert operation of MyBatis, how to return the primary key while inserting data? There are two cases. One case is that the primary key is an auto-incrementing primary key, and the other is that the primary key is not auto-incrementing. Next, the two cases will be explained in detail.

MySQL supports auto-incrementing primary keys, while Oracle does not support auto-incrementing primary keys. You can use getGeneratedKeys()methods to obtain auto-incrementing primary keys in JDBC .

Get the value of the auto-incrementing primary key
  • Interface in CompetitionMapper.java
int createCompetition(Competition competition);
  • How to write xml in CompetitionMapper.xml
<insert id="createCompetition" useGeneratedKeys="true" parameterType="com.ebusiness.reviewer.model.Competition" keyProperty="id">
  insert into 
  	competition  
  		(id,c_name,start_time,end_time,create_time)
  values 
  	(default ,#{cname},#{startTime},#{endTime},NOW()})
</insert>

The above usage useGeneratedKeys="true"means using the self-incrementing primary key acquisition strategy to keyPropertyspecify the corresponding primary key attribute, that is, after MyBatis obtains the primary key, which attribute of javaBean will encapsulate this value.

  • Call the createCompetition method in CompetitionMapper.java in CompetitionService.java and the way to receive the self-incrementing primary key.
//competitionMapper是注入到容器中的CompetitionMapper对象,competition是传入的对象
competitionMapper.createCompetition(competition);
//id 就是自增主键
int id = competition.getId();
Method of obtaining non-auto-incrementing primary key
 <insert id="createCompetition" parameterType="com.ebusiness.reviewer.model.Competition">
	<selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
		SELECT uuid()
	</selectKey>
	insert into 
		competition  
			(id,c_name,start_time,end_time,create_time)
	values 
		(#{id},#{cname},#{startTime},#{endTime},NOW())
</insert>

keyProperty: Set the queried primary key to which attribute in parameterType.
Order: Relative to the execution order of the SQL statement, BEFORE means query the primary key before inserting.
resultType: Specify the return value type

  • Query the value of the non-incrementing primary key in the selectKey tag, and then assign it to the value of the primary key to be inserted in the insert.

  • Database debug mode print log
    Insert picture description here

  • After calling the method to receive a non-incremental primary key
    Insert picture description here

  • Console print log
    Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43941676/article/details/108699020