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); Article findById(@Param("id") String id);
boolean findTag(@Param("tagName") String tagName); Tag findTag(@Param("tagName") String tagName);
void insertTag(@Param("tag") Tag tag); void insertTag(@Param("tag") Tag tag);

View File

@ -29,10 +29,11 @@ public class MyBatisArticleRepository implements ArticleRepository {
private void createNew(Article article) { private void createNew(Article article) {
for (Tag tag : article.getTags()) { for (Tag tag : article.getTags()) {
if (!articleMapper.findTag(tag.getName())) { Tag targetTag = Optional.ofNullable(articleMapper.findTag(tag.getName())).orElseGet(() -> {
articleMapper.insertTag(tag); articleMapper.insertTag(tag);
} return tag;
articleMapper.insertArticleTagRelation(article.getId(), tag.getId()); });
articleMapper.insertArticleTagRelation(article.getId(), targetTag.getId());
} }
articleMapper.insert(article); articleMapper.insert(article);
} }

View File

@ -54,9 +54,10 @@
where A.id = #{id} where A.id = #{id}
</select> </select>
<select id="findTag" resultType="java.lang.Boolean"> <select id="findTag" resultType="io.spring.core.article.Tag">
select count(*) from tags where name = #{tagName} select id, name from tags where name = #{tagName}
</select> </select>
<select id="findBySlug" resultMap="article"> <select id="findBySlug" resultMap="article">
<include refid="selectArticle"/> <include refid="selectArticle"/>
where A.slug = #{slug} 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 org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest @SpringBootTest
@ -38,7 +39,7 @@ public class ArticleRepositoryTransactionTest {
try { try {
articleRepository.save(anotherArticle); articleRepository.save(anotherArticle);
} catch (Exception e) { } catch (Exception e) {
assertFalse(articleMapper.findTag("other")); assertNull(articleMapper.findTag("other"));
} }
} }