Fix existed tag insert failed for articles

This commit is contained in:
xushanchuan 2020-11-26 15:48:38 +08:00
parent be7aa410e6
commit d8bb60f999
No known key found for this signature in database
GPG Key ID: 44D23C44E00838D6
4 changed files with 10 additions and 7 deletions

View File

@ -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);

View File

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

View File

@ -54,9 +54,10 @@
where A.id = #{id}
</select>
<select id="findTag" resultType="java.lang.Boolean">
select count(*) from tags where name = #{tagName}
<select id="findTag" resultType="io.spring.core.article.Tag">
select id, name from tags where name = #{tagName}
</select>
<select id="findBySlug" resultMap="article">
<include refid="selectArticle"/>
where A.slug = #{slug}

View File

@ -13,6 +13,7 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
@RunWith(SpringRunner.class)
@SpringBootTest
@ -38,7 +39,7 @@ public class ArticleRepositoryTransactionTest {
try {
articleRepository.save(anotherArticle);
} catch (Exception e) {
assertFalse(articleMapper.findTag("other"));
assertNull(articleMapper.findTag("other"));
}
}