Mybatis插入语句返回主键ID

Mybatis插入语句返回主键ID

1,主键为自增
1),mapper.xml的sql语句
<insert id="insert" parameterType="gtd.qicke.com.pojo.Article" useGeneratedKeys="true"
            keyProperty="articleId">
        insert into
        <include refid="tb"/>
        (article_user_id, article_title,
        article_view_count, article_comment_count,
        article_like_count, article_create_time, article_update_time,
        article_is_comment, article_status, article_order,
        article_content,article_cover,article_cover_type)
        values (#{articleUserId,jdbcType=INTEGER}, #{articleTitle,jdbcType=VARCHAR},
        #{articleViewCount,jdbcType=INTEGER},
        #{articleCommentCount,jdbcType=INTEGER},
        #{articleLikeCount,jdbcType=INTEGER}, #{articleCreateTime,jdbcType=TIMESTAMP},
        #{articleUpdateTime,jdbcType=TIMESTAMP},
        #{articleIsComment,jdbcType=INTEGER}, #{articleStatus,jdbcType=INTEGER}, #{articleOrder,jdbcType=INTEGER},
        #{articleContent,jdbcType=LONGVARCHAR},#{coverUrl,jdbcType=VARCHAR},#{coverType,jdbcType=INTEGER})
    </insert>

记得加上useGeneratedKeys和keyProperty配置

1,useGeneratedKeys是指设置是否使用jdbc的getGenereatedKeys方法获取主键并赋值到keyProperty设置的属性中
2,keyProperty即实体类主键字段

2),dao层接口
public interface ArticleMapper {

    /**
     * 添加文章
     *
     * @param article 文章
     * @return 文章
     */
    Integer insert(Article article);
}
3),service层
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    
    @Override
    public void insertArticle(Article article) {
        //添加文章
        article.setArticleViewCount(0);
        article.setArticleLikeCount(0);
        article.setArticleCommentCount(0);
        article.setArticleOrder(1);
        //插入语句
        articleMapper.insert(article);
        //添加分类和文章关联egoryId());

		//获取插入后返回的主键id(articleId)
        Integer articleId = article.getArticleId();
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值