fix: 使用 join 联表查询一个对象,数据丢失。

This commit is contained in:
Suomm 2023-06-08 12:32:55 +08:00
parent 4e5d9913bb
commit d56b886db0
2 changed files with 39 additions and 22 deletions

View File

@ -1,4 +1,4 @@
/**
/*
* Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
@ -345,8 +345,7 @@ public interface BaseMapper<T> {
* @return entity 数据
*/
default T selectOneByQuery(QueryWrapper queryWrapper) {
List<T> entities = selectListByQuery(queryWrapper.limit(1));
return (entities == null || entities.isEmpty()) ? null : entities.get(0);
return SqlUtil.getSelectOneResult(selectListByQuery(queryWrapper));
}
@ -358,8 +357,7 @@ public interface BaseMapper<T> {
* @return 数据内容
*/
default <R> R selectOneByQueryAs(QueryWrapper queryWrapper, Class<R> asType) {
List<R> entities = selectListByQueryAs(queryWrapper.limit(1), asType);
return (entities == null || entities.isEmpty()) ? null : entities.get(0);
return SqlUtil.getSelectOneResult(selectListByQueryAs(queryWrapper, asType));
}
/**
@ -495,8 +493,7 @@ public interface BaseMapper<T> {
* @return 数据量
*/
default Object selectObjectByQuery(QueryWrapper queryWrapper) {
List<Object> objects = selectObjectListByQuery(queryWrapper.limit(1));
return objects == null || objects.isEmpty() ? null : objects.get(0);
return SqlUtil.getSelectOneResult(selectObjectListByQuery(queryWrapper));
}

View File

@ -15,13 +15,18 @@
*/
package com.mybatisflex.core.util;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.apache.ibatis.session.defaults.DefaultSqlSession;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
public class SqlUtil {
private SqlUtil() {}
private SqlUtil() {
}
public static void keepColumnSafely(String column) {
if (StringUtil.isBlank(column)) {
@ -108,4 +113,19 @@ public class SqlUtil {
return sql;
}
/**
* 搬运加改造 {@link DefaultSqlSession#selectOne(String, Object)}
*/
public static <T> T getSelectOneResult(List<T> list) {
if (list == null || list.isEmpty()) {
return null;
}
int size = list.size();
if (size == 1) {
return list.get(0);
}
throw new TooManyResultsException(
"Expected one result (or null) to be returned by selectOne(), but found: " + size);
}
}