public interface CuisineMapper {
int insert(Cuisine record);
int insertSelective(Cuisine record);
}
注意:返回的是操作的成功条数
<insert id="insertSelective" parameterType="com.freshidentification.backstage.pojo.Cuisine" useGeneratedKeys="true" keyProperty="id">
insert into cuisine
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="introduction != null">
introduction,
</if>
<if test="image != null">
image,
</if>
<if test="viewedQuantity != null">
viewed_quantity,
</if>
<if test="collectionQuantity != null">
collection_quantity,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="introduction != null">
#{introduction,jdbcType=VARCHAR},
</if>
<if test="image != null">
#{image,jdbcType=VARCHAR},
</if>
<if test="viewedQuantity != null">
#{viewedQuantity,jdbcType=INTEGER},
</if>
<if test="collectionQuantity != null">
#{collectionQuantity,jdbcType=INTEGER},
</if>
</trim>
</insert>
关键是加上useGeneratedKeys=“true” keyProperty=“id”
调用场景:
Cuisine cuisine = new Cuisine();
cuisine.setName(cuisineDTO.getName());
cuisine.setImage(cuisineDTO.getImage());
cuisine.setIntroduction(cuisineDTO.getIntroduction());
int i2 = cuisineMapper.insertSelective(cuisine);
if (i2 == 0) {
return ResultVO.fail(PageCodeEnum.Deal_Fail,
"更新菜谱表失败");
}
int cuisineId = cuisine.getId();
之前错误地认为加上useGeneratedKeys="true" keyProperty="id" 会改变insert 方法的返回值,其实不然,返回值不会改变,改变的是会将主键传回到传入insert 方法的实体中!
查了大量资料尝试无果,非常感谢该文章的启发:MyBatis insert返回主键不成功
|