diff --git a/mybatis-flex-core/src/main/java/com/mybatisflex/core/service/IService.java b/mybatis-flex-core/src/main/java/com/mybatisflex/core/service/IService.java index 816a5820..7300ee30 100644 --- a/mybatis-flex-core/src/main/java/com/mybatisflex/core/service/IService.java +++ b/mybatis-flex-core/src/main/java/com/mybatisflex/core/service/IService.java @@ -18,9 +18,7 @@ package com.mybatisflex.core.service; import com.mybatisflex.core.BaseMapper; import com.mybatisflex.core.exception.FlexExceptions; import com.mybatisflex.core.paginate.Page; -import com.mybatisflex.core.query.QueryChain; -import com.mybatisflex.core.query.QueryCondition; -import com.mybatisflex.core.query.QueryWrapper; +import com.mybatisflex.core.query.*; import com.mybatisflex.core.row.Db; import com.mybatisflex.core.update.UpdateChain; import com.mybatisflex.core.util.ClassUtil; @@ -495,7 +493,7 @@ public interface IService { * @return {@code true} 数据存在,{@code false} 数据不存在。 */ default boolean exists(QueryWrapper query) { - return CollectionUtil.isNotEmpty(getMapper().selectListByQuery(query.limit(1))); + return exists(CPI.getWhereQueryCondition(query)); } /** @@ -505,7 +503,15 @@ public interface IService { * @return {@code true} 数据存在,{@code false} 数据不存在。 */ default boolean exists(QueryCondition condition) { - return CollectionUtil.isNotEmpty(getMapper().selectListByCondition(condition, 1L)); + // 根据查询条件构建 SQL 语句 + // SELECT 1 FROM table WHERE ... LIMIT 1 + QueryWrapper queryWrapper = QueryMethods.selectOne() + .where(condition) + .limit(1); + // 获取数据集合,空集合:[] 不存在数据,有一个元素的集合:[1] 存在数据 + List objects = getMapper().selectObjectListByQuery(queryWrapper); + // 判断是否存在数据 + return CollectionUtil.isNotEmpty(objects); } /** diff --git a/mybatis-flex-test/mybatis-flex-spring-boot-test/src/test/java/com/mybatisflex/test/service/ArticleServiceTest.java b/mybatis-flex-test/mybatis-flex-spring-boot-test/src/test/java/com/mybatisflex/test/service/ArticleServiceTest.java index 4936386d..7062152e 100644 --- a/mybatis-flex-test/mybatis-flex-spring-boot-test/src/test/java/com/mybatisflex/test/service/ArticleServiceTest.java +++ b/mybatis-flex-test/mybatis-flex-spring-boot-test/src/test/java/com/mybatisflex/test/service/ArticleServiceTest.java @@ -16,6 +16,7 @@ package com.mybatisflex.test.service; +import com.mybatisflex.core.query.QueryWrapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -42,4 +43,15 @@ class ArticleServiceTest { .forEach(System.out::println); } + @Test + void testExists() { + QueryWrapper queryWrapper = QueryWrapper.create() + .select(ARTICLE.DEFAULT_COLUMNS) + .from(ARTICLE) + .where(ARTICLE.ACCOUNT_ID.eq(1)) + .orderBy(ARTICLE.ACCOUNT_ID.desc()); + boolean exists = articleService.exists(queryWrapper); + System.out.println(exists); + } + }