The solution to the problem of using @ Param for Mybatis parameter to insert and return the primary key

Keywords: Java SQL Mybatis Attribute

Today, when working on the project, I encountered the problem that I need to return the auto increment primary key ID of the data just inserted. I found that the getId returned from the object is always empty, and all the data I checked online are

Similar to this,
 <insert id="insertAndgetkey" parameterType="com.soft.mybatis.model.User">
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into t_user (username,password,create_date) values(#{username},#            
       {password},#{createDate})
</insert>

The corresponding dao is of this type

int insertAndGeyKey(User user);

However, @ Param annotation is used in my project, and two parameters are passed in as follows:

public Long insertExpression(@Param("orgId") Long orgId,@Param("expression") EventEmotionExpression expression);

At the beginning, my sql file was written as follows:

<insert id="insertExpression" >
		<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
			select last_insert_id()
		</selectKey>
		insert into event_emotion_expression_#{orgId}
		  <include refid="columns"/>
		values(
			#{expression.eventId},#{expression.name},
			#{expression.weight},#{expression.categoryId},
			#{expression.sourceStartTime},#{expression.sourceEndTime},
			#{expression.insertDate}
		)
	</insert>

After a long time, I found that the returned ID was always null, and I began to doubt my life. Later, I finally made a breakthrough, because the selectkey tag is responsible for querying the primary key ID used in this data insertion and then copying it to the corresponding keyProperty on one property, while my ID attribute is on the expression object, and only one ID written must not be assigned, so keyprop The property of erty needs to be written as "expression.id", which is a perfect solution.

The final sql file is:

<insert id="insertExpression" >
		<selectKey keyProperty="expression.id" order="AFTER" resultType="java.lang.Long">
			select last_insert_id()
		</selectKey>
		insert into event_emotion_expression_#{orgId}
		  <include refid="columns"/>
		values(
			#{expression.eventId},#{expression.name},
			#{expression.weight},#{expression.categoryId},
			#{expression.sourceStartTime},#{expression.sourceEndTime},
			#{expression.insertDate}
		)
	</insert>

 

Posted by unidox on Sun, 05 Jan 2020 01:21:30 -0800