9 Commits
Author SHA1 Message Date
timi 35c63c4b83 Merge pull request 'v0.0.20' (#20) from dev into master
Reviewed-on: #20
2026-09-17 17:51:23 +00:00
Timi 25c3944d5f v0.0.20
CI/CD / build-deploy (pull_request) Successful in 15s
2026-09-18 01:48:43 +08:00
Timi ba9fa7ef97 support Boolean for page 2026-09-18 01:48:34 +08:00
timi c9c7c098c8 Merge pull request 'v0.0.19' (#19) from dev into master
Reviewed-on: #19
2026-08-11 15:59:26 +00:00
Timi a4a9317731 v0.0.19
CI/CD / build-deploy (pull_request) Successful in 13s
2026-08-11 23:59:02 +08:00
timi cf701b18fa Merge pull request 'v0.0.18' (#18) from dev into master
Reviewed-on: #18
2026-08-03 11:57:18 +00:00
Timi f42b833e3e v0.0.18
CI/CD / build-deploy (pull_request) Successful in 13s
2026-08-03 19:57:05 +08:00
timi ebaeb1ac56 Merge pull request 'v0.0.17' (#17) from dev into master
Reviewed-on: #17
2026-07-31 17:12:36 +00:00
Timi 7e1ff1343d v0.0.17
CI/CD / build-deploy (pull_request) Successful in 13s
2026-08-01 01:12:18 +08:00
10 changed files with 229 additions and 103 deletions
+11 -1
View File
@@ -13,7 +13,7 @@
<groupId>com.imyeyu.spring</groupId>
<artifactId>timi-spring</artifactId>
<version>0.0.16</version>
<version>0.0.20</version>
<packaging>jar</packaging>
<properties>
@@ -141,6 +141,16 @@
<dependency>
<groupId>com.imyeyu.io</groupId>
<artifactId>timi-io</artifactId>
<version>0.0.6</version>
</dependency>
<dependency>
<groupId>com.imyeyu.java</groupId>
<artifactId>timi-java</artifactId>
<version>0.0.6</version>
</dependency>
<dependency>
<groupId>com.imyeyu.lang</groupId>
<artifactId>timi-lang</artifactId>
<version>0.0.5</version>
</dependency>
<dependency>
@@ -10,7 +10,7 @@ import java.lang.annotation.Target;
/**
* 应用在 Controller 的接口上
*
* <p>{@link #lifeCycle()} 生命周期内(秒)限制访问 {@link #value()} 次
* <p>{@link #inSeconds()} 生命周期内(秒)限制访问 {@link #value()} 次
*
* @author 夜雨
* @version 2021-08-16 17:57
@@ -32,5 +32,5 @@ public @interface RequestRateLimit {
*
* @return 生命周期秒数
*/
int lifeCycle() default 10;
int inSeconds() default 10;
}
@@ -45,7 +45,7 @@ public abstract class RequestRateLimitAbstractInterceptor implements HandlerInte
return true;
}
// 频率限制
return beforeRun(req, resp, buildId(handlerMethod), requestRateLimit.lifeCycle(), requestRateLimit.value());
return beforeRun(req, resp, buildId(handlerMethod), requestRateLimit.inSeconds(), requestRateLimit.value());
}
return true;
}
@@ -37,34 +37,6 @@ public class Page<T> extends BasePage {
/** 排序字段映射 */
protected LinkedHashMap<String, BaseMapper.OrderType> orderMap;
/**
* 创建分页参数
*
* @param index 页码
* @param size 每页数量
*/
public Page(int index, int size) {
super(index, size);
}
/**
* 获取偏移量
*
* @return 偏移量
*/
public long getOffset() {
return (long) index * size;
}
/**
* 获取限制数量
*
* @return 限制数量
*/
public long getLimit() {
return size;
}
/**
* 添加排序字段
*
@@ -31,6 +31,7 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
@@ -81,6 +82,21 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildSelectByPageSQL(EntityMeta meta, String tableName, Page<?> page, String offset, String limit) {
return buildSelectByPageSQL(meta, tableName, page, offset, limit, "");
}
/**
* 构建分页查询 SQL
*
* @param meta 实体元数据
* @param tableName 表名
* @param page 分页参数
* @param offset 偏移量占位符
* @param limit 限制数量占位符
* @param pageParameterPath Page 参数路径前缀
* @return SQL
*/
protected String buildSelectByPageSQL(EntityMeta meta, String tableName, Page<?> page, String offset, String limit, String pageParameterPath) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT %s FROM `%s` WHERE 1 = 1".formatted(meta.selectPageClause, tableName));
@@ -88,7 +104,11 @@ public abstract class BaseSQLProvider {
appendSoftDeleteCondition(sql, meta);
// 添加 Page 查询条件
if (pageParameterPath.isEmpty()) {
appendPageConditions(sql, page);
} else {
appendPageConditions(sql, page, pageParameterPath);
}
// 添加排序
appendOrderBy(sql, meta, page);
@@ -107,6 +127,19 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildCountByPageSQL(EntityMeta meta, String tableName, Page<?> page) {
return buildCountByPageSQL(meta, tableName, page, "");
}
/**
* 构建分页统计 SQL
*
* @param meta 实体元数据
* @param tableName 表名
* @param page 分页参数
* @param pageParameterPath Page 参数路径前缀
* @return SQL
*/
protected String buildCountByPageSQL(EntityMeta meta, String tableName, Page<?> page, String pageParameterPath) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT COUNT(*) FROM `%s` WHERE 1 = 1".formatted(tableName));
@@ -114,7 +147,11 @@ public abstract class BaseSQLProvider {
appendSoftDeleteCondition(sql, meta);
// 添加 Page 查询条件
if (pageParameterPath.isEmpty()) {
appendPageConditions(sql, page);
} else {
appendPageConditions(sql, page, pageParameterPath);
}
return sql.toString();
}
@@ -138,30 +175,82 @@ public abstract class BaseSQLProvider {
* @param page 分页参数
*/
protected void appendPageConditions(StringBuilder sql, Page<?> page) {
appendPageConditions(sql, page, "");
}
/**
* 添加 Page 查询条件
*
* @param sql SQL 构建器
* @param page 分页参数
* @param pageParameterPath Page 参数路径前缀
*/
protected void appendPageConditions(StringBuilder sql, Page<?> page, String pageParameterPath) {
// 精准查询
if (TimiJava.isNotEmpty(page.getEqualsExample())) {
Object obj = page.getEqualsExample();
EntityMeta metaExample = getEntityMeta(obj.getClass());
String conditionClause = metaExample.fieldColumnList.stream()
.filter(fc -> fc.isNotEmpty(obj))
.map(fc -> "`%s` = '%s'".formatted(fc.columnName, fc.getAsString(obj)))
.collect(Collectors.joining(" %s ".formatted(page.getEqualsLogic())));
if (TimiJava.isNotEmpty(conditionClause)) {
sql.append(" AND ").append(conditionClause);
}
}
appendPageExampleConditions(
sql,
page.getEqualsExample(),
page.getEqualsLogic(),
false,
pageParameterPath
);
// 模糊查询
if (TimiJava.isNotEmpty(page.getLikesExample())) {
Object obj = page.getLikesExample();
EntityMeta metaExample = getEntityMeta(obj.getClass());
appendPageExampleConditions(
sql,
page.getLikesExample(),
page.getLikesLogic(),
true,
pageParameterPath
);
}
/**
* 添加一组 Page 示例条件
*
* @param sql SQL 构建器
* @param example 示例对象
* @param logic 条件连接逻辑
* @param likes 是否使用模糊匹配
* @param pageParameterPath Page 参数路径前缀
*/
private void appendPageExampleConditions(StringBuilder sql, Object example, Logic logic, boolean likes, String pageParameterPath) {
if (TimiJava.isEmpty(example)) {
return;
}
EntityMeta metaExample = getEntityMeta(example.getClass());
String parameterPrefix = "%s%s.".formatted(pageParameterPath, likes ? "likesExample" : "equalsExample");
String conditionClause = metaExample.fieldColumnList.stream()
.filter(fc -> fc.isNotEmpty(obj))
.map(fc -> "`%s` LIKE CONCAT('%%', '%s', '%%')".formatted(fc.columnName, fc.getAsString(obj)))
.collect(Collectors.joining(" %s ".formatted(page.getLikesLogic())));
.map(fc -> buildPageCondition(fc, example, likes, parameterPrefix))
.filter(Objects::nonNull)
.collect(Collectors.joining(" %s ".formatted(logic == null ? Logic.AND : logic)));
if (TimiJava.isNotEmpty(conditionClause)) {
sql.append(" AND (").append(conditionClause).append(')');
}
}
/**
* 构建单个 Page 示例条件
*
* @param fieldColumn 字段元数据
* @param example 示例对象
* @param likes 是否使用模糊匹配
* @param parameterPrefix 参数路径前缀
* @return 条件子句;字段值为空时返回 null
*/
private String buildPageCondition(FieldColumn fieldColumn, Object example, boolean likes, String parameterPrefix) {
Object value = fieldColumn.getValue(example);
if (TimiJava.isEmpty(value)) {
return null;
}
if (value instanceof Boolean booleanValue) {
return "`%s` IS %s".formatted(fieldColumn.columnName, booleanValue ? "TRUE" : "FALSE");
}
String parameter = "#{%s%s}".formatted(parameterPrefix, fieldColumn.fieldName);
if (likes) {
return "`%s` LIKE CONCAT('%%', %s, '%%')".formatted(fieldColumn.columnName, parameter);
}
return "`%s` = %s".formatted(fieldColumn.columnName, parameter);
}
/**
@@ -231,7 +320,7 @@ public abstract class BaseSQLProvider {
Ref.setFieldValue(entity, fc.field, uuid);
}
} catch (IllegalAccessException e) {
throw new TimiException(TimiCode.ERROR).msgKey("auto set field:%s value error".formatted(fc.fieldName));
throw new TimiException(TimiCode.ERROR, "auto set field:%s value error".formatted(fc.fieldName));
}
if (entity instanceof Creatable creatableEntity && creatableEntity.getCreatedAt() == null) {
creatableEntity.setCreatedAt(Time.now());
@@ -648,11 +737,7 @@ public abstract class BaseSQLProvider {
* @return true 为 null
*/
public boolean isNull(Object entity) {
try {
return Ref.getFieldValue(entity, field, Object.class) == null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return getValue(entity) == null;
}
/**
@@ -672,11 +757,7 @@ public abstract class BaseSQLProvider {
* @return true 为空
*/
public boolean isEmpty(Object entity) {
try {
return TimiJava.isEmpty(Ref.getFieldValue(entity, field, Object.class));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return TimiJava.isEmpty(getValue(entity));
}
/**
@@ -696,8 +777,18 @@ public abstract class BaseSQLProvider {
* @return 字符串值
*/
public String getAsString(Object obj) {
return getValue(obj).toString();
}
/**
* 获取字段值
*
* @param entity 实体
* @return 字段值
*/
public Object getValue(Object entity) {
try {
return field.get(obj).toString();
return Ref.getFieldValue(entity, field, Object.class);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
@@ -25,7 +25,7 @@ public class DynamicTableSQLProvider extends BaseSQLProvider {
*/
public String selectByPage(ProviderContext context, @Param("tableName") String tableName, @Param("page") Page<?> page) {
EntityMeta meta = getEntityMeta(context);
return buildSelectByPageSQL(meta, tableName, page, "#{page.offset}", "#{page.limit}");
return buildSelectByPageSQL(meta, tableName, page, "#{page.offset}", "#{page.limit}", "page.");
}
/**
@@ -38,7 +38,7 @@ public class DynamicTableSQLProvider extends BaseSQLProvider {
*/
public String countByPage(ProviderContext context, @Param("tableName") String tableName, @Param("page") Page<?> page) {
EntityMeta meta = getEntityMeta(context);
return buildCountByPageSQL(meta, tableName, page);
return buildCountByPageSQL(meta, tableName, page, "page.");
}
/**
@@ -1,8 +1,11 @@
package com.imyeyu.spring.util;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiError;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.java.bean.timi.TimiResponse;
import com.imyeyu.lang.message.MessageResolver;
import com.imyeyu.spring.TimiSpring;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import jakarta.servlet.ServletException;
@@ -11,6 +14,7 @@ import jakarta.validation.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindException;
@@ -30,10 +34,15 @@ public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
private final ObjectProvider<MessageResolver> messageResolverProvider;
/**
* 创建全局异常处理器
*
* @param messageResolverProvider 消息解析器提供器
*/
public GlobalExceptionHandler() {
public GlobalExceptionHandler(ObjectProvider<MessageResolver> messageResolverProvider) {
this.messageResolverProvider = messageResolverProvider;
}
@Value("${spring.profiles.active}")
@@ -55,7 +64,7 @@ public class GlobalExceptionHandler {
if (ignoreCommittedBinaryResponse()) {
return null;
}
return new TimiResponse<>(TimiCode.ARG_BAD).msgKey("invalid.body");
return fail(TimiCode.ARG_BAD, "invalid.body");
}
/**
@@ -74,7 +83,7 @@ public class GlobalExceptionHandler {
if (ignoreCommittedBinaryResponse()) {
return null;
}
return new TimiResponse<>(TimiCode.REQUEST_BAD).msgKey("invalid.request");
return fail(TimiCode.REQUEST_BAD, "invalid.request");
}
/**
@@ -83,19 +92,20 @@ public class GlobalExceptionHandler {
* @param e 异常
* @return 异常返回
*/
@IgnoreGlobalReturn
@ExceptionHandler({BindException.class, ValidationException.class, MethodArgumentNotValidException.class, TypeMismatchException.class})
public TimiResponse<?> paramsException(Exception e) {
if (e instanceof MethodArgumentNotValidException subE) {
log.warn("request error", e);
FieldError error = subE.getBindingResult().getFieldError();
if (error != null) {
return new TimiResponse<>(TimiCode.ARG_BAD, "[%s] %s".formatted(error.getField(), error.getDefaultMessage()));
return fail(TimiCode.ARG_BAD, "[%s] %s".formatted(error.getField(), error.getDefaultMessage()));
}
}
if (env.startsWith("dev") || log.isDebugEnabled()) {
log.error("request error", e);
}
return new TimiResponse<>(TimiCode.REQUEST_BAD).msgKey("invalid.arg");
return fail(TimiCode.REQUEST_BAD, "invalid.arg");
}
/**
@@ -114,15 +124,81 @@ public class GlobalExceptionHandler {
if (ignoreCommittedBinaryResponse()) {
return null;
}
// 一般异常
return timiE.toResponse();
return fail(timiE);
}
if (e instanceof TimiError timiE) {
log.error(timiE.getMessage(), e);
if (ignoreCommittedBinaryResponse()) {
return null;
}
return fail(timiE.getCode(), timiE.getMessageCode(), timiE.getMessageArgs());
}
// 致命异常
log.error("fatal error", e);
if (ignoreCommittedBinaryResponse()) {
return null;
}
return new TimiResponse<>(TimiCode.ERROR).msgKey("service.error");
return fail(TimiCode.ERROR, "service.error");
}
/**
* 创建失败响应
*
* @param e 异常
* @return 响应
*/
private TimiResponse<?> fail(TimiException e) {
return fail(e.getCode(), e.getMessageCode(), e.getMessageArgs());
}
/**
* 创建失败响应
*
* @param code 代码
* @param messageCode 消息代码
* @return 响应
*/
private TimiResponse<?> fail(TimiCode code, String messageCode) {
return fail(code, messageCode, null);
}
/**
* 创建失败响应
*
* @param code 代码
* @param messageCode 消息代码
* @param messageArgs 消息插值参数
* @return 响应
*/
private TimiResponse<?> fail(TimiCode code, String messageCode, java.util.Map<String, Object> messageArgs) {
TimiResponse<?> result = new TimiResponse<>(code).messageCode(messageCode, messageArgs);
result.setMessage(resolveMessage(code, messageCode, messageArgs));
return result;
}
/**
* 解析消息
*
* @param code 代码
* @param messageCode 消息代码
* @param messageArgs 消息插值参数
* @return 消息
*/
private String resolveMessage(TimiCode code, String messageCode, java.util.Map<String, Object> messageArgs) {
if (TimiJava.isEmpty(messageCode)) {
return code.toString();
}
try {
MessageResolver messageResolver = messageResolverProvider.getIfAvailable();
if (messageResolver == null) {
return messageCode;
}
String message = messageResolver.resolve(messageCode, messageArgs, TimiSpring.getLanguage());
return TimiJava.isEmpty(message) ? messageCode : message;
} catch (Exception e) {
log.error("message resolve error", e);
return messageCode;
}
}
/**
@@ -1,14 +1,10 @@
package com.imyeyu.spring.util;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.CallbackArgReturn;
import com.imyeyu.java.bean.LanguageMsgMapping;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiResponse;
import com.imyeyu.spring.TimiSpring;
import com.imyeyu.spring.annotation.AOPLogInterceptor;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
@@ -28,15 +24,11 @@ import java.util.Objects;
* @author 夜雨
* @version 2023-04-30 00:59
*/
@Data
@RestControllerAdvice
public class GlobalReturnHandler implements ResponseBodyAdvice<Object> {
private static final Logger log = LoggerFactory.getLogger(GlobalReturnHandler.class);
/** 多语言头处理回调 */
private CallbackArgReturn<LanguageMsgMapping<?>, String> multilingualHeader;
/**
* 创建全局返回处理器
*/
@@ -59,23 +51,12 @@ public class GlobalReturnHandler implements ResponseBodyAdvice<Object> {
{
TimiResponse<?> result;
if (body instanceof TimiResponse<?> timiResponse) {
// 可能已被全局异常包装
result = timiResponse;
} else {
result = new TimiResponse<>(TimiCode.SUCCESS, body);
}
try {
if (multilingualHeader != null && TimiJava.isNotEmpty(result.getMsgKey())) {
result.setMsg(multilingualHeader.handler(result));
} else if (TimiJava.isEmpty(result.getMsg())) {
result.setMsg(TimiCode.fromCode(result.getCode()).toString());
}
} catch (Exception e) {
log.error("multilingual response error", e);
result.setMsg(TimiCode.fromCode(result.getCode()).toString());
}
if (30000 < result.getCode()) {
log.warn("ID: {} Response -> Exception.{}.{}", TimiSpring.getSessionAttr(AOPLogInterceptor.REQUEST_ID), result.getCode(), result.getMsg());
log.warn("ID: {} Response -> Exception.{}.{}", TimiSpring.getSessionAttr(AOPLogInterceptor.REQUEST_ID), result.getCode(), result.getMessage());
}
return result;
}
@@ -4,8 +4,6 @@ import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.config.AbstractRedisConfig;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
@@ -30,8 +28,6 @@ import java.util.function.Consumer;
* @author 夜雨
* @version 2021-11-21 09:58
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Redis<K, V> {
@@ -30,7 +30,7 @@ public class SQLProvider extends BaseSQLProvider {
*/
public String selectByPage(ProviderContext context, @Param("page") Page<?> page) {
EntityMeta meta = getEntityMeta(context);
return buildSelectByPageSQL(meta, meta.table, page, "#{offset}", "#{limit}");
return buildSelectByPageSQL(meta, meta.table, page, "#{offset}", "#{limit}", "");
}
/**
@@ -42,7 +42,7 @@ public class SQLProvider extends BaseSQLProvider {
*/
public String countByPage(ProviderContext context, @Param("page") Page<?> page) {
EntityMeta meta = getEntityMeta(context);
return buildCountByPageSQL(meta, meta.table, page);
return buildCountByPageSQL(meta, meta.table, page, "");
}
/**