useGeneratedKeys
在mybatis的XML映射器中设置useGeneratedKeys=true,是为了在执行insert 、update操作后能获取操作成功后的插入对象的自增主键id
keyProperty
keyProperty指定在Java 实体类中对应的主键
keyColumn
keyColumn指的是数据库表中自增主键的字段名
插入数据时,实体类中未提供id值 通过在xml中设置参数,mybatis会设置传过去的实体类goodsReview中Id的值,先插入数据后把数据库中自动生成的Id值映射到实体类goodsReview中Id里,方便service层中后续操作。前提该数据是主键且可以在数据库中自动生成
keyColumn="id" keyProperty="id" useGeneratedKeys="true"
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GoodsReview {
private Integer id;
private String goodId;
private String userId;
private String reviewContent;
}
service层
@Service
public class GoodsReviewService {
@Resource
private GoodsReviewMapper goodsReviewMapper;
public GoodsReview addReview(GoodsReview goodsReview) {
return goodsReviewMapper.addReview(goodsReview);
}
}
Mapper层
@Mapper
public interface GoodsReviewMapper {
GoodsReview addReview(GoodsReview goodsReview);
}
xml
<insert id="addReview" keyColumn="id" keyProperty="id" parameterType="com.onlinestore.pojo.GoodsReview"
useGeneratedKeys="true">
insert into goods_review (good_id, user_id, review_content
)
values (#{goodId,jdbcType=VARCHAR}, #{userId,jdbcType=VARCHAR}, #{reviewContent,jdbcType=LONGVARCHAR}
)
</insert>
数据前后变化:
{
"Id":"",
"goodId":"111",
"userId":"123tt",
"reviewContent":"tttttttttttttttt"
}
变为
{
"Id":"123",
"goodId":"111",
"userId":"123tt",
"reviewContent":"tttttttttttttttt"
}
参考文章: 文章1 : https://blog.csdn.net/Du939/article/details/100014905. 文章2 : https://blog.csdn.net/sinat_30474567/article/details/51395247.
|