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();
}
}