From d8bb60f999360fa3127ee8a05ffb7a5b15de178e Mon Sep 17 00:00:00 2001 From: xushanchuan Date: Thu, 26 Nov 2020 15:48:38 +0800 Subject: [PATCH] Fix existed tag insert failed for articles --- .../infrastructure/mybatis/mapper/ArticleMapper.java | 2 +- .../repository/MyBatisArticleRepository.java | 7 ++++--- src/main/resources/mapper/ArticleMapper.xml | 5 +++-- .../article/ArticleRepositoryTransactionTest.java | 3 ++- 4 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/main/java/io/spring/infrastructure/mybatis/mapper/ArticleMapper.java b/src/main/java/io/spring/infrastructure/mybatis/mapper/ArticleMapper.java index 9005e23..14d8b24 100644 --- a/src/main/java/io/spring/infrastructure/mybatis/mapper/ArticleMapper.java +++ b/src/main/java/io/spring/infrastructure/mybatis/mapper/ArticleMapper.java @@ -11,7 +11,7 @@ public interface ArticleMapper { Article findById(@Param("id") String id); - boolean findTag(@Param("tagName") String tagName); + Tag findTag(@Param("tagName") String tagName); void insertTag(@Param("tag") Tag tag); diff --git a/src/main/java/io/spring/infrastructure/repository/MyBatisArticleRepository.java b/src/main/java/io/spring/infrastructure/repository/MyBatisArticleRepository.java index 056dd01..bc2411c 100644 --- a/src/main/java/io/spring/infrastructure/repository/MyBatisArticleRepository.java +++ b/src/main/java/io/spring/infrastructure/repository/MyBatisArticleRepository.java @@ -29,10 +29,11 @@ public class MyBatisArticleRepository implements ArticleRepository { private void createNew(Article article) { for (Tag tag : article.getTags()) { - if (!articleMapper.findTag(tag.getName())) { + Tag targetTag = Optional.ofNullable(articleMapper.findTag(tag.getName())).orElseGet(() -> { articleMapper.insertTag(tag); - } - articleMapper.insertArticleTagRelation(article.getId(), tag.getId()); + return tag; + }); + articleMapper.insertArticleTagRelation(article.getId(), targetTag.getId()); } articleMapper.insert(article); } diff --git a/src/main/resources/mapper/ArticleMapper.xml b/src/main/resources/mapper/ArticleMapper.xml index eedaf10..60a9811 100644 --- a/src/main/resources/mapper/ArticleMapper.xml +++ b/src/main/resources/mapper/ArticleMapper.xml @@ -54,9 +54,10 @@ where A.id = #{id} - + select id, name from tags where name = #{tagName} +