!312 feat:优化 exists 方法执行效率

Merge pull request !312 from 王帅/main
This commit is contained in:
Michael Yang 2023-08-25 22:35:04 +00:00 committed by Gitee
commit 1718f83fb2
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
2 changed files with 23 additions and 5 deletions

View File

@ -18,9 +18,7 @@ package com.mybatisflex.core.service;
import com.mybatisflex.core.BaseMapper; import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.exception.FlexExceptions; import com.mybatisflex.core.exception.FlexExceptions;
import com.mybatisflex.core.paginate.Page; import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryChain; import com.mybatisflex.core.query.*;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db; import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.update.UpdateChain; import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.core.util.ClassUtil; import com.mybatisflex.core.util.ClassUtil;
@ -495,7 +493,7 @@ public interface IService<T> {
* @return {@code true} 数据存在{@code false} 数据不存在 * @return {@code true} 数据存在{@code false} 数据不存在
*/ */
default boolean exists(QueryWrapper query) { 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<T> {
* @return {@code true} 数据存在{@code false} 数据不存在 * @return {@code true} 数据存在{@code false} 数据不存在
*/ */
default boolean exists(QueryCondition condition) { 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<Object> objects = getMapper().selectObjectListByQuery(queryWrapper);
// 判断是否存在数据
return CollectionUtil.isNotEmpty(objects);
} }
/** /**

View File

@ -16,6 +16,7 @@
package com.mybatisflex.test.service; package com.mybatisflex.test.service;
import com.mybatisflex.core.query.QueryWrapper;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
@ -42,4 +43,15 @@ class ArticleServiceTest {
.forEach(System.out::println); .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);
}
} }