Compare commits
2
Commits
25c3944d5f
...
c7dc033bad
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7dc033bad | ||
|
|
a1726bf3b2 |
@@ -13,7 +13,7 @@
|
|||||||
|
|
||||||
<groupId>com.imyeyu.spring</groupId>
|
<groupId>com.imyeyu.spring</groupId>
|
||||||
<artifactId>timi-spring</artifactId>
|
<artifactId>timi-spring</artifactId>
|
||||||
<version>0.0.20</version>
|
<version>0.1.0</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
@@ -138,20 +138,10 @@
|
|||||||
<artifactId>commons-pool2</artifactId>
|
<artifactId>commons-pool2</artifactId>
|
||||||
<version>2.13.1</version>
|
<version>2.13.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<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>
|
<dependency>
|
||||||
<groupId>com.imyeyu.lang</groupId>
|
<groupId>com.imyeyu.lang</groupId>
|
||||||
<artifactId>timi-lang</artifactId>
|
<artifactId>timi-lang</artifactId>
|
||||||
<version>0.0.5</version>
|
<version>0.1.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ package com.imyeyu.spring;
|
|||||||
|
|
||||||
import com.imyeyu.io.IO;
|
import com.imyeyu.io.IO;
|
||||||
import com.imyeyu.java.TimiJava;
|
import com.imyeyu.java.TimiJava;
|
||||||
import com.imyeyu.java.bean.Language;
|
import com.imyeyu.java.bean.ActionException;
|
||||||
import com.imyeyu.java.bean.timi.TimiCode;
|
import com.imyeyu.java.bean.ResultCode;
|
||||||
import com.imyeyu.java.bean.timi.TimiException;
|
|
||||||
import com.imyeyu.java.ref.Ref;
|
import com.imyeyu.java.ref.Ref;
|
||||||
|
import com.imyeyu.lang.bean.Language;
|
||||||
import com.imyeyu.spring.bean.RequestRange;
|
import com.imyeyu.spring.bean.RequestRange;
|
||||||
import jakarta.servlet.http.Cookie;
|
import jakarta.servlet.http.Cookie;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
@@ -45,13 +45,13 @@ public class TimiSpring {
|
|||||||
* 获取 Servlet 请求属性
|
* 获取 Servlet 请求属性
|
||||||
*
|
*
|
||||||
* @return Servlet 请求属性
|
* @return Servlet 请求属性
|
||||||
* @throws TimiException 请求异常
|
* @throws ActionException 请求异常
|
||||||
*/
|
*/
|
||||||
public static ServletRequestAttributes getServletRequestAttributes() {
|
public static ServletRequestAttributes getServletRequestAttributes() {
|
||||||
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes sra) {
|
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes sra) {
|
||||||
return sra;
|
return sra;
|
||||||
}
|
}
|
||||||
throw new TimiException(TimiCode.ERROR_NPE_VARIABLE);
|
throw new ActionException(ResultCode.ERROR_NPE_VARIABLE);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -109,7 +109,7 @@ public class TimiSpring {
|
|||||||
*/
|
*/
|
||||||
public static String cutURIStartAt(String flag) {
|
public static String cutURIStartAt(String flag) {
|
||||||
int indexOf = getURI().indexOf(flag);
|
int indexOf = getURI().indexOf(flag);
|
||||||
TimiException.requiredTrue(-1 < indexOf, "not found flag: %s".formatted(flag));
|
ActionException.requiredTrue(-1 < indexOf, "not found flag: %s".formatted(flag));
|
||||||
return getURI().substring(indexOf + flag.length());
|
return getURI().substring(indexOf + flag.length());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -399,7 +399,7 @@ public class TimiSpring {
|
|||||||
* 获取请求 IP
|
* 获取请求 IP
|
||||||
*
|
*
|
||||||
* @return 请求 IP
|
* @return 请求 IP
|
||||||
* @throws TimiException 服务异常
|
* @throws ActionException 服务异常
|
||||||
*/
|
*/
|
||||||
public static String getRequestIP() {
|
public static String getRequestIP() {
|
||||||
String ip = getHeader("x-forwarded-for");
|
String ip = getHeader("x-forwarded-for");
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.imyeyu.spring.annotation;
|
||||||
|
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 标记需要在响应阶段自动回填的多语言字段
|
||||||
|
*
|
||||||
|
* @author 夜雨
|
||||||
|
* @since 2026-07-17 00:00
|
||||||
|
*/
|
||||||
|
@Target({ElementType.FIELD})
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
public @interface MultilingualField {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多语言 ID 来源字段名
|
||||||
|
*
|
||||||
|
* @return 来源字段名
|
||||||
|
*/
|
||||||
|
String value();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 模板参数来源字段名
|
||||||
|
*
|
||||||
|
* @return 同类中的 Map 字段名
|
||||||
|
*/
|
||||||
|
String argMap() default "";
|
||||||
|
}
|
||||||
@@ -3,8 +3,8 @@ package com.imyeyu.spring.annotation;
|
|||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.imyeyu.java.TimiJava;
|
import com.imyeyu.java.TimiJava;
|
||||||
import com.imyeyu.java.bean.timi.TimiCode;
|
import com.imyeyu.java.bean.ResultCode;
|
||||||
import com.imyeyu.java.bean.timi.TimiException;
|
import com.imyeyu.java.bean.ActionException;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import org.springframework.core.MethodParameter;
|
import org.springframework.core.MethodParameter;
|
||||||
import org.springframework.lang.NonNull;
|
import org.springframework.lang.NonNull;
|
||||||
@@ -48,7 +48,7 @@ public class RequestBodyValueArgumentResolver implements HandlerMethodArgumentRe
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
|
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
|
||||||
TimiException.required(request, "not found request");
|
ActionException.required(request, "not found request");
|
||||||
assert request != null;
|
assert request != null;
|
||||||
|
|
||||||
JsonNode requestBody;
|
JsonNode requestBody;
|
||||||
@@ -58,9 +58,9 @@ public class RequestBodyValueArgumentResolver implements HandlerMethodArgumentRe
|
|||||||
return jsonNode;
|
return jsonNode;
|
||||||
}
|
}
|
||||||
byte[] bodyBytes = request.getInputStream().readAllBytes();
|
byte[] bodyBytes = request.getInputStream().readAllBytes();
|
||||||
TimiException.requiredTrue(1 < bodyBytes.length, "empty request body");
|
ActionException.requiredTrue(1 < bodyBytes.length, "empty request body");
|
||||||
requestBody = objectMapper.readTree(bodyBytes);
|
requestBody = objectMapper.readTree(bodyBytes);
|
||||||
TimiException.requiredTrue(requestBody != null && requestBody.isObject(), "not object request body");
|
ActionException.requiredTrue(requestBody != null && requestBody.isObject(), "not object request body");
|
||||||
request.setAttribute(REQUEST_BODY_JSON_NODE_ATTR, requestBody);
|
request.setAttribute(REQUEST_BODY_JSON_NODE_ATTR, requestBody);
|
||||||
}
|
}
|
||||||
String fieldName = bodyValue.value();
|
String fieldName = bodyValue.value();
|
||||||
@@ -68,14 +68,14 @@ public class RequestBodyValueArgumentResolver implements HandlerMethodArgumentRe
|
|||||||
if (TimiJava.isEmpty(fieldName)) {
|
if (TimiJava.isEmpty(fieldName)) {
|
||||||
fieldName = parameter.getParameterName();
|
fieldName = parameter.getParameterName();
|
||||||
}
|
}
|
||||||
TimiException.required(fieldName, "not found @RequestBodyValue parameter name");
|
ActionException.required(fieldName, "not found @RequestBodyValue parameter name");
|
||||||
}
|
}
|
||||||
JsonNode fieldNode = requestBody.get(fieldName);
|
JsonNode fieldNode = requestBody.get(fieldName);
|
||||||
if (fieldNode == null || fieldNode.isMissingNode() || fieldNode.isNull()) {
|
if (fieldNode == null || fieldNode.isMissingNode() || fieldNode.isNull()) {
|
||||||
if (!bodyValue.required()) {
|
if (!bodyValue.required()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
throw new TimiException(TimiCode.ARG_MISS, "not found json field: %s".formatted(fieldName));
|
throw new ActionException(ResultCode.ARG_MISS, "not found json field: %s".formatted(fieldName));
|
||||||
}
|
}
|
||||||
return objectMapper.treeToValue(fieldNode, parameter.getParameterType());
|
return objectMapper.treeToValue(fieldNode, parameter.getParameterType());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
package com.imyeyu.spring.entity;
|
package com.imyeyu.spring.entity;
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonView;
|
import com.fasterxml.jackson.annotation.JsonView;
|
||||||
import com.imyeyu.java.bean.Language;
|
import com.imyeyu.lang.bean.Language;
|
||||||
import com.imyeyu.java.ref.Ref;
|
import com.imyeyu.lang.bean.MultilingualValue;
|
||||||
import com.imyeyu.spring.annotation.table.AutoUUID;
|
import com.imyeyu.spring.annotation.table.AutoUUID;
|
||||||
import com.imyeyu.spring.annotation.table.Id;
|
import com.imyeyu.spring.annotation.table.Id;
|
||||||
import com.imyeyu.spring.util.ResponseView;
|
import com.imyeyu.spring.util.ResponseView;
|
||||||
@@ -17,7 +17,7 @@ import lombok.EqualsAndHashCode;
|
|||||||
*/
|
*/
|
||||||
@Data
|
@Data
|
||||||
@EqualsAndHashCode(callSuper = true)
|
@EqualsAndHashCode(callSuper = true)
|
||||||
public class Multilingual extends Language implements IDEntity<String>, Creatable, Updatable, Deletable, Destroyable {
|
public class Multilingual extends Language implements MultilingualValue, IDEntity<String>, Creatable, Updatable, Deletable, Destroyable {
|
||||||
|
|
||||||
/** 唯一标识 */
|
/** 唯一标识 */
|
||||||
@Id
|
@Id
|
||||||
@@ -40,18 +40,4 @@ public class Multilingual extends Language implements IDEntity<String>, Creatabl
|
|||||||
/** 删除时间 */
|
/** 删除时间 */
|
||||||
@JsonView(ResponseView.Admin.class)
|
@JsonView(ResponseView.Admin.class)
|
||||||
protected Long deletedAt;
|
protected Long deletedAt;
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取指定语言值
|
|
||||||
*
|
|
||||||
* @param language 指定语言
|
|
||||||
* @return 值
|
|
||||||
*/
|
|
||||||
public String getValue(Language.Enum language) {
|
|
||||||
try {
|
|
||||||
return Ref.getFieldValue(this, language.toString().replace("_", ""), String.class);
|
|
||||||
} catch (IllegalAccessException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package com.imyeyu.spring.service;
|
package com.imyeyu.spring.service;
|
||||||
|
|
||||||
import com.imyeyu.java.bean.timi.TimiException;
|
import com.imyeyu.java.bean.ActionException;
|
||||||
import com.imyeyu.spring.bean.Page;
|
import com.imyeyu.spring.bean.Page;
|
||||||
import com.imyeyu.spring.bean.PageResult;
|
import com.imyeyu.spring.bean.PageResult;
|
||||||
import com.imyeyu.spring.entity.Deletable;
|
import com.imyeyu.spring.entity.Deletable;
|
||||||
@@ -32,7 +32,7 @@ public abstract class AbstractEntityService<T, P> implements BaseService<T, P> {
|
|||||||
if (baseMapper == null) {
|
if (baseMapper == null) {
|
||||||
baseMapper = mapper();
|
baseMapper = mapper();
|
||||||
}
|
}
|
||||||
TimiException.required(baseMapper, "mapper() can not be null");
|
ActionException.required(baseMapper, "mapper() can not be null");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package com.imyeyu.spring.service;
|
package com.imyeyu.spring.service;
|
||||||
|
|
||||||
import com.imyeyu.java.bean.timi.TimiException;
|
import com.imyeyu.java.bean.ActionException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 可创建实体服务
|
* 可创建实体服务
|
||||||
@@ -15,7 +15,7 @@ public interface CreatableService<T> {
|
|||||||
* 创建数据
|
* 创建数据
|
||||||
*
|
*
|
||||||
* @param t 数据对象
|
* @param t 数据对象
|
||||||
* @throws TimiException 服务异常
|
* @throws ActionException 服务异常
|
||||||
*/
|
*/
|
||||||
void create(T t);
|
void create(T t);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package com.imyeyu.spring.service;
|
package com.imyeyu.spring.service;
|
||||||
|
|
||||||
import com.imyeyu.java.bean.timi.TimiException;
|
import com.imyeyu.java.bean.ActionException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 可软删除实体服务
|
* 可软删除实体服务
|
||||||
@@ -15,7 +15,7 @@ public interface DeletableService<P> {
|
|||||||
* 软删除
|
* 软删除
|
||||||
*
|
*
|
||||||
* @param p 数据对象
|
* @param p 数据对象
|
||||||
* @throws TimiException 服务异常
|
* @throws ActionException 服务异常
|
||||||
*/
|
*/
|
||||||
void delete(P p);
|
void delete(P p);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package com.imyeyu.spring.service;
|
package com.imyeyu.spring.service;
|
||||||
|
|
||||||
import com.imyeyu.java.bean.timi.TimiException;
|
import com.imyeyu.java.bean.ActionException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 可销毁(物理删除)实体服务
|
* 可销毁(物理删除)实体服务
|
||||||
@@ -15,7 +15,7 @@ public interface DestroyableService<P> {
|
|||||||
* 销毁(物理删除)
|
* 销毁(物理删除)
|
||||||
*
|
*
|
||||||
* @param p 数据对象
|
* @param p 数据对象
|
||||||
* @throws TimiException 服务异常
|
* @throws ActionException 服务异常
|
||||||
*/
|
*/
|
||||||
void destroy(P p);
|
void destroy(P p);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package com.imyeyu.spring.service;
|
package com.imyeyu.spring.service;
|
||||||
|
|
||||||
import com.imyeyu.java.bean.timi.TimiException;
|
import com.imyeyu.java.bean.ActionException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 可更新实体服务
|
* 可更新实体服务
|
||||||
@@ -15,7 +15,7 @@ public interface UpdatableService<T> {
|
|||||||
* 修改数据
|
* 修改数据
|
||||||
*
|
*
|
||||||
* @param t 数据对象
|
* @param t 数据对象
|
||||||
* @throws TimiException 服务异常
|
* @throws ActionException 服务异常
|
||||||
*/
|
*/
|
||||||
void update(T t);
|
void update(T t);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ package com.imyeyu.spring.util;
|
|||||||
|
|
||||||
import com.imyeyu.java.TimiJava;
|
import com.imyeyu.java.TimiJava;
|
||||||
import com.imyeyu.java.bean.CallbackArgReturn;
|
import com.imyeyu.java.bean.CallbackArgReturn;
|
||||||
import com.imyeyu.java.bean.timi.TimiCode;
|
import com.imyeyu.java.bean.ResultCode;
|
||||||
import com.imyeyu.java.bean.timi.TimiException;
|
import com.imyeyu.java.bean.ActionException;
|
||||||
import com.imyeyu.java.ref.Ref;
|
import com.imyeyu.java.ref.Ref;
|
||||||
import com.imyeyu.spring.annotation.table.AutoUUID;
|
import com.imyeyu.spring.annotation.table.AutoUUID;
|
||||||
import com.imyeyu.spring.annotation.table.Column;
|
import com.imyeyu.spring.annotation.table.Column;
|
||||||
@@ -320,7 +320,7 @@ public abstract class BaseSQLProvider {
|
|||||||
Ref.setFieldValue(entity, fc.field, uuid);
|
Ref.setFieldValue(entity, fc.field, uuid);
|
||||||
}
|
}
|
||||||
} catch (IllegalAccessException e) {
|
} catch (IllegalAccessException e) {
|
||||||
throw new TimiException(TimiCode.ERROR, "auto set field:%s value error".formatted(fc.fieldName));
|
throw new ActionException(ResultCode.ERROR, "auto set field:%s value error".formatted(fc.fieldName));
|
||||||
}
|
}
|
||||||
if (entity instanceof Creatable creatableEntity && creatableEntity.getCreatedAt() == null) {
|
if (entity instanceof Creatable creatableEntity && creatableEntity.getCreatedAt() == null) {
|
||||||
creatableEntity.setCreatedAt(Time.now());
|
creatableEntity.setCreatedAt(Time.now());
|
||||||
@@ -339,7 +339,7 @@ public abstract class BaseSQLProvider {
|
|||||||
* @return SQL
|
* @return SQL
|
||||||
*/
|
*/
|
||||||
protected String buildSelectByIdSQL(EntityMeta meta, String tableName, String idParam) {
|
protected String buildSelectByIdSQL(EntityMeta meta, String tableName, String idParam) {
|
||||||
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||||
|
|
||||||
StringBuilder sql = new StringBuilder();
|
StringBuilder sql = new StringBuilder();
|
||||||
sql.append("SELECT %s FROM `%s` WHERE `%s` = #{%s}".formatted(
|
sql.append("SELECT %s FROM `%s` WHERE `%s` = #{%s}".formatted(
|
||||||
@@ -388,8 +388,8 @@ public abstract class BaseSQLProvider {
|
|||||||
* @return SQL
|
* @return SQL
|
||||||
*/
|
*/
|
||||||
protected String buildUpdateSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix) {
|
protected String buildUpdateSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix) {
|
||||||
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||||
TimiException.required(meta.canUpdate, "not allow update for %s".formatted(meta.entityClass));
|
ActionException.required(meta.canUpdate, "not allow update for %s".formatted(meta.entityClass));
|
||||||
|
|
||||||
if (entity instanceof Updatable updatable) {
|
if (entity instanceof Updatable updatable) {
|
||||||
updatable.setUpdatedAt(Time.now());
|
updatable.setUpdatedAt(Time.now());
|
||||||
@@ -417,8 +417,8 @@ public abstract class BaseSQLProvider {
|
|||||||
* @return SQL
|
* @return SQL
|
||||||
*/
|
*/
|
||||||
protected String buildUpdateSelectiveSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix) {
|
protected String buildUpdateSelectiveSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix) {
|
||||||
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||||
TimiException.required(meta.canUpdate, "not allow update for %s".formatted(meta.entityClass));
|
ActionException.required(meta.canUpdate, "not allow update for %s".formatted(meta.entityClass));
|
||||||
|
|
||||||
if (entity instanceof Updatable updatable) {
|
if (entity instanceof Updatable updatable) {
|
||||||
updatable.setUpdatedAt(Time.now());
|
updatable.setUpdatedAt(Time.now());
|
||||||
@@ -446,8 +446,8 @@ public abstract class BaseSQLProvider {
|
|||||||
* @return SQL
|
* @return SQL
|
||||||
*/
|
*/
|
||||||
protected String buildDeleteSQL(EntityMeta meta, String tableName, String idParam) {
|
protected String buildDeleteSQL(EntityMeta meta, String tableName, String idParam) {
|
||||||
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||||
TimiException.requiredTrue(meta.canDelete, "not allow soft delete for %s".formatted(meta.entityClass));
|
ActionException.requiredTrue(meta.canDelete, "not allow soft delete for %s".formatted(meta.entityClass));
|
||||||
|
|
||||||
return "UPDATE `%s` SET `deleted_at` = %s WHERE `%s` = #{%s}".formatted(
|
return "UPDATE `%s` SET `deleted_at` = %s WHERE `%s` = #{%s}".formatted(
|
||||||
tableName,
|
tableName,
|
||||||
@@ -468,13 +468,13 @@ public abstract class BaseSQLProvider {
|
|||||||
* @return SQL
|
* @return SQL
|
||||||
*/
|
*/
|
||||||
protected String buildDeleteAllByExampleSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix, Logic logic) {
|
protected String buildDeleteAllByExampleSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix, Logic logic) {
|
||||||
TimiException.required(meta.canDelete, "not allow delete for %s".formatted(meta.entityClass));
|
ActionException.required(meta.canDelete, "not allow delete for %s".formatted(meta.entityClass));
|
||||||
|
|
||||||
FieldColumn deleteColumn = meta.getFieldColumnList().stream()
|
FieldColumn deleteColumn = meta.getFieldColumnList().stream()
|
||||||
.filter(fc -> fc.isDeleteColumn)
|
.filter(fc -> fc.isDeleteColumn)
|
||||||
.findFirst()
|
.findFirst()
|
||||||
.orElse(null);
|
.orElse(null);
|
||||||
TimiException.required(deleteColumn, "unknown delete column, use com.imyeyu.spring.annotation.table.DeleteColumn annotation on field");
|
ActionException.required(deleteColumn, "unknown delete column, use com.imyeyu.spring.annotation.table.DeleteColumn annotation on field");
|
||||||
assert deleteColumn != null;
|
assert deleteColumn != null;
|
||||||
assert deleteColumn.deleteColumnType != null;
|
assert deleteColumn.deleteColumnType != null;
|
||||||
|
|
||||||
@@ -501,8 +501,8 @@ public abstract class BaseSQLProvider {
|
|||||||
* @return SQL
|
* @return SQL
|
||||||
*/
|
*/
|
||||||
protected String buildDestroySQL(EntityMeta meta, String tableName, String idParam) {
|
protected String buildDestroySQL(EntityMeta meta, String tableName, String idParam) {
|
||||||
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||||
TimiException.requiredTrue(meta.canDestroy, "not allow destroy for %s".formatted(meta.entityClass));
|
ActionException.requiredTrue(meta.canDestroy, "not allow destroy for %s".formatted(meta.entityClass));
|
||||||
|
|
||||||
return "DELETE FROM `%s` WHERE `%s` = #{%s}".formatted(tableName, meta.idFieldColumn.columnName, idParam);
|
return "DELETE FROM `%s` WHERE `%s` = #{%s}".formatted(tableName, meta.idFieldColumn.columnName, idParam);
|
||||||
}
|
}
|
||||||
@@ -518,7 +518,7 @@ public abstract class BaseSQLProvider {
|
|||||||
* @return SQL
|
* @return SQL
|
||||||
*/
|
*/
|
||||||
protected String buildDestroyAllByExampleSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix, Logic logic) {
|
protected String buildDestroyAllByExampleSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix, Logic logic) {
|
||||||
TimiException.required(meta.canDestroy, "not allow destroy for %s".formatted(meta.entityClass));
|
ActionException.required(meta.canDestroy, "not allow destroy for %s".formatted(meta.entityClass));
|
||||||
String destroyClause = meta.fieldColumnList.stream()
|
String destroyClause = meta.fieldColumnList.stream()
|
||||||
.filter(FieldColumn::isNotId)
|
.filter(FieldColumn::isNotId)
|
||||||
.filter(fc -> fc.isNotEmpty(entity))
|
.filter(fc -> fc.isNotEmpty(entity))
|
||||||
@@ -583,7 +583,7 @@ public abstract class BaseSQLProvider {
|
|||||||
this.table = Text.camelCase2underscore(entityClass.getSimpleName());
|
this.table = Text.camelCase2underscore(entityClass.getSimpleName());
|
||||||
} else {
|
} else {
|
||||||
this.table = table.value();
|
this.table = table.value();
|
||||||
TimiException.required(this.table, String.format("empty table annotation value for %s entity", entityClass.getName()));
|
ActionException.required(this.table, String.format("empty table annotation value for %s entity", entityClass.getName()));
|
||||||
}
|
}
|
||||||
List<Field> allFieldList = Ref.listAllFields(entityClass);
|
List<Field> allFieldList = Ref.listAllFields(entityClass);
|
||||||
FieldColumn idFieldColumn = null;
|
FieldColumn idFieldColumn = null;
|
||||||
@@ -595,7 +595,7 @@ public abstract class BaseSQLProvider {
|
|||||||
}
|
}
|
||||||
FieldColumn fieldColumn = new FieldColumn(field);
|
FieldColumn fieldColumn = new FieldColumn(field);
|
||||||
if (fieldColumn.isId) {
|
if (fieldColumn.isId) {
|
||||||
TimiException.requiredNull(idFieldColumn, String.format("multi id field for %s entity", entityClass.getName()));
|
ActionException.requiredNull(idFieldColumn, String.format("multi id field for %s entity", entityClass.getName()));
|
||||||
idFieldColumn = fieldColumn;
|
idFieldColumn = fieldColumn;
|
||||||
}
|
}
|
||||||
fieldColumnList.add(fieldColumn);
|
fieldColumnList.add(fieldColumn);
|
||||||
@@ -713,7 +713,7 @@ public abstract class BaseSQLProvider {
|
|||||||
columnName = Text.camelCase2underscore(field.getName());
|
columnName = Text.camelCase2underscore(field.getName());
|
||||||
} else {
|
} else {
|
||||||
columnName = column.value();
|
columnName = column.value();
|
||||||
TimiException.required(columnName, "empty field:%s column annotation value for %s entity".formatted(field.getName(), field.getDeclaringClass()));
|
ActionException.required(columnName, "empty field:%s column annotation value for %s entity".formatted(field.getName(), field.getDeclaringClass()));
|
||||||
}
|
}
|
||||||
isId = field.isAnnotationPresent(Id.class);
|
isId = field.isAnnotationPresent(Id.class);
|
||||||
isAutoUUID = field.isAnnotationPresent(AutoUUID.class);
|
isAutoUUID = field.isAnnotationPresent(AutoUUID.class);
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
package com.imyeyu.spring.util;
|
package com.imyeyu.spring.util;
|
||||||
|
|
||||||
import com.imyeyu.java.TimiJava;
|
import com.imyeyu.java.TimiJava;
|
||||||
import com.imyeyu.java.bean.timi.TimiCode;
|
import com.imyeyu.java.bean.ActionError;
|
||||||
import com.imyeyu.java.bean.timi.TimiError;
|
import com.imyeyu.java.bean.ActionException;
|
||||||
import com.imyeyu.java.bean.timi.TimiException;
|
import com.imyeyu.java.bean.Response;
|
||||||
import com.imyeyu.java.bean.timi.TimiResponse;
|
import com.imyeyu.java.bean.ResultCode;
|
||||||
import com.imyeyu.lang.message.MessageResolver;
|
import com.imyeyu.lang.MultilingualResolver;
|
||||||
import com.imyeyu.spring.TimiSpring;
|
import com.imyeyu.spring.TimiSpring;
|
||||||
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
|
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
|
||||||
import jakarta.servlet.ServletException;
|
import jakarta.servlet.ServletException;
|
||||||
@@ -34,15 +34,15 @@ public class GlobalExceptionHandler {
|
|||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||||
|
|
||||||
private final ObjectProvider<MessageResolver> messageResolverProvider;
|
private final ObjectProvider<MultilingualResolver> multilingualResolverProvider;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建全局异常处理器
|
* 创建全局异常处理器
|
||||||
*
|
*
|
||||||
* @param messageResolverProvider 消息解析器提供器
|
* @param multilingualResolverProvider 消息解析器提供器
|
||||||
*/
|
*/
|
||||||
public GlobalExceptionHandler(ObjectProvider<MessageResolver> messageResolverProvider) {
|
public GlobalExceptionHandler(ObjectProvider<MultilingualResolver> multilingualResolverProvider) {
|
||||||
this.messageResolverProvider = messageResolverProvider;
|
this.multilingualResolverProvider = multilingualResolverProvider;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Value("${spring.profiles.active}")
|
@Value("${spring.profiles.active}")
|
||||||
@@ -64,7 +64,7 @@ public class GlobalExceptionHandler {
|
|||||||
if (ignoreCommittedBinaryResponse()) {
|
if (ignoreCommittedBinaryResponse()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return fail(TimiCode.ARG_BAD, "invalid.body");
|
return fail(ResultCode.ARG_BAD, "invalid.body");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -83,7 +83,7 @@ public class GlobalExceptionHandler {
|
|||||||
if (ignoreCommittedBinaryResponse()) {
|
if (ignoreCommittedBinaryResponse()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return fail(TimiCode.REQUEST_BAD, "invalid.request");
|
return fail(ResultCode.REQUEST_BAD, "invalid.request");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -94,18 +94,18 @@ public class GlobalExceptionHandler {
|
|||||||
*/
|
*/
|
||||||
@IgnoreGlobalReturn
|
@IgnoreGlobalReturn
|
||||||
@ExceptionHandler({BindException.class, ValidationException.class, MethodArgumentNotValidException.class, TypeMismatchException.class})
|
@ExceptionHandler({BindException.class, ValidationException.class, MethodArgumentNotValidException.class, TypeMismatchException.class})
|
||||||
public TimiResponse<?> paramsException(Exception e) {
|
public Response<?> paramsException(Exception e) {
|
||||||
if (e instanceof MethodArgumentNotValidException subE) {
|
if (e instanceof MethodArgumentNotValidException subE) {
|
||||||
log.warn("request error", e);
|
log.warn("request error", e);
|
||||||
FieldError error = subE.getBindingResult().getFieldError();
|
FieldError error = subE.getBindingResult().getFieldError();
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
return fail(TimiCode.ARG_BAD, "[%s] %s".formatted(error.getField(), error.getDefaultMessage()));
|
return fail(ResultCode.ARG_BAD, "[%s] %s".formatted(error.getField(), error.getDefaultMessage()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (env.startsWith("dev") || log.isDebugEnabled()) {
|
if (env.startsWith("dev") || log.isDebugEnabled()) {
|
||||||
log.error("request error", e);
|
log.error("request error", e);
|
||||||
}
|
}
|
||||||
return fail(TimiCode.REQUEST_BAD, "invalid.arg");
|
return fail(ResultCode.REQUEST_BAD, "invalid.arg");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -117,7 +117,7 @@ public class GlobalExceptionHandler {
|
|||||||
@IgnoreGlobalReturn
|
@IgnoreGlobalReturn
|
||||||
@ExceptionHandler(Throwable.class)
|
@ExceptionHandler(Throwable.class)
|
||||||
public Object error(Throwable e) {
|
public Object error(Throwable e) {
|
||||||
if (e instanceof TimiException timiE) {
|
if (e instanceof ActionException timiE) {
|
||||||
if (!env.startsWith("prod") || log.isDebugEnabled()) {
|
if (!env.startsWith("prod") || log.isDebugEnabled()) {
|
||||||
log.error(timiE.getMessage(), e);
|
log.error(timiE.getMessage(), e);
|
||||||
}
|
}
|
||||||
@@ -126,19 +126,19 @@ public class GlobalExceptionHandler {
|
|||||||
}
|
}
|
||||||
return fail(timiE);
|
return fail(timiE);
|
||||||
}
|
}
|
||||||
if (e instanceof TimiError timiE) {
|
if (e instanceof ActionError actionE) {
|
||||||
log.error(timiE.getMessage(), e);
|
log.error(actionE.getMessage(), e);
|
||||||
if (ignoreCommittedBinaryResponse()) {
|
if (ignoreCommittedBinaryResponse()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return fail(timiE.getCode(), timiE.getMessageCode(), timiE.getMessageArgs());
|
return fail(actionE.getCode(), actionE.getMessageCode(), actionE.getMessageArgs());
|
||||||
}
|
}
|
||||||
// 致命异常
|
// 致命异常
|
||||||
log.error("fatal error", e);
|
log.error("fatal error", e);
|
||||||
if (ignoreCommittedBinaryResponse()) {
|
if (ignoreCommittedBinaryResponse()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return fail(TimiCode.ERROR, "service.error");
|
return fail(ResultCode.ERROR, "service.error");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -147,7 +147,7 @@ public class GlobalExceptionHandler {
|
|||||||
* @param e 异常
|
* @param e 异常
|
||||||
* @return 响应
|
* @return 响应
|
||||||
*/
|
*/
|
||||||
private TimiResponse<?> fail(TimiException e) {
|
private Response<?> fail(ActionException e) {
|
||||||
return fail(e.getCode(), e.getMessageCode(), e.getMessageArgs());
|
return fail(e.getCode(), e.getMessageCode(), e.getMessageArgs());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,7 +158,7 @@ public class GlobalExceptionHandler {
|
|||||||
* @param messageCode 消息代码
|
* @param messageCode 消息代码
|
||||||
* @return 响应
|
* @return 响应
|
||||||
*/
|
*/
|
||||||
private TimiResponse<?> fail(TimiCode code, String messageCode) {
|
private Response<?> fail(ResultCode code, String messageCode) {
|
||||||
return fail(code, messageCode, null);
|
return fail(code, messageCode, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -170,8 +170,8 @@ public class GlobalExceptionHandler {
|
|||||||
* @param messageArgs 消息插值参数
|
* @param messageArgs 消息插值参数
|
||||||
* @return 响应
|
* @return 响应
|
||||||
*/
|
*/
|
||||||
private TimiResponse<?> fail(TimiCode code, String messageCode, java.util.Map<String, Object> messageArgs) {
|
private Response<?> fail(ResultCode code, String messageCode, java.util.Map<String, Object> messageArgs) {
|
||||||
TimiResponse<?> result = new TimiResponse<>(code).messageCode(messageCode, messageArgs);
|
Response<?> result = new Response<>(code).messageCode(messageCode, messageArgs);
|
||||||
result.setMessage(resolveMessage(code, messageCode, messageArgs));
|
result.setMessage(resolveMessage(code, messageCode, messageArgs));
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -184,16 +184,16 @@ public class GlobalExceptionHandler {
|
|||||||
* @param messageArgs 消息插值参数
|
* @param messageArgs 消息插值参数
|
||||||
* @return 消息
|
* @return 消息
|
||||||
*/
|
*/
|
||||||
private String resolveMessage(TimiCode code, String messageCode, java.util.Map<String, Object> messageArgs) {
|
private String resolveMessage(ResultCode code, String messageCode, java.util.Map<String, Object> messageArgs) {
|
||||||
if (TimiJava.isEmpty(messageCode)) {
|
if (TimiJava.isEmpty(messageCode)) {
|
||||||
return code.toString();
|
return code.toString();
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
MessageResolver messageResolver = messageResolverProvider.getIfAvailable();
|
MultilingualResolver messageResolver = multilingualResolverProvider.getIfAvailable();
|
||||||
if (messageResolver == null) {
|
if (messageResolver == null) {
|
||||||
return messageCode;
|
return messageCode;
|
||||||
}
|
}
|
||||||
String message = messageResolver.resolve(messageCode, messageArgs, TimiSpring.getLanguage());
|
String message = messageResolver.map(TimiSpring.getLanguage()).message(messageCode, messageArgs);
|
||||||
return TimiJava.isEmpty(message) ? messageCode : message;
|
return TimiJava.isEmpty(message) ? messageCode : message;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("message resolve error", e);
|
log.error("message resolve error", e);
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
package com.imyeyu.spring.util;
|
package com.imyeyu.spring.util;
|
||||||
|
|
||||||
import com.imyeyu.java.bean.timi.TimiCode;
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
import com.imyeyu.java.bean.timi.TimiResponse;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.imyeyu.java.bean.Response;
|
||||||
|
import com.imyeyu.java.bean.ResultCode;
|
||||||
import com.imyeyu.spring.TimiSpring;
|
import com.imyeyu.spring.TimiSpring;
|
||||||
import com.imyeyu.spring.annotation.AOPLogInterceptor;
|
import com.imyeyu.spring.annotation.AOPLogInterceptor;
|
||||||
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
|
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
|
||||||
@@ -10,6 +12,7 @@ import org.slf4j.LoggerFactory;
|
|||||||
import org.springframework.core.MethodParameter;
|
import org.springframework.core.MethodParameter;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.converter.HttpMessageConverter;
|
import org.springframework.http.converter.HttpMessageConverter;
|
||||||
|
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||||
import org.springframework.http.server.ServerHttpRequest;
|
import org.springframework.http.server.ServerHttpRequest;
|
||||||
import org.springframework.http.server.ServerHttpResponse;
|
import org.springframework.http.server.ServerHttpResponse;
|
||||||
import org.springframework.lang.NonNull;
|
import org.springframework.lang.NonNull;
|
||||||
@@ -19,7 +22,7 @@ import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
|||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 全局返回处理器,包装 TimiResponse
|
* 全局返回处理器,包装 Response
|
||||||
*
|
*
|
||||||
* @author 夜雨
|
* @author 夜雨
|
||||||
* @version 2023-04-30 00:59
|
* @version 2023-04-30 00:59
|
||||||
@@ -28,11 +31,15 @@ import java.util.Objects;
|
|||||||
public class GlobalReturnHandler implements ResponseBodyAdvice<Object> {
|
public class GlobalReturnHandler implements ResponseBodyAdvice<Object> {
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(GlobalReturnHandler.class);
|
private static final Logger log = LoggerFactory.getLogger(GlobalReturnHandler.class);
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建全局返回处理器
|
* 创建全局返回处理器
|
||||||
|
*
|
||||||
|
* @param objectMapper JSON 对象映射器
|
||||||
*/
|
*/
|
||||||
public GlobalReturnHandler() {
|
public GlobalReturnHandler(ObjectMapper objectMapper) {
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -47,17 +54,25 @@ public class GlobalReturnHandler implements ResponseBodyAdvice<Object> {
|
|||||||
@NonNull MediaType selectedContentType,
|
@NonNull MediaType selectedContentType,
|
||||||
@NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
|
@NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
|
||||||
@NonNull ServerHttpRequest request,
|
@NonNull ServerHttpRequest request,
|
||||||
@NonNull ServerHttpResponse response)
|
@NonNull ServerHttpResponse response
|
||||||
{
|
) {
|
||||||
TimiResponse<?> result;
|
Response<?> result;
|
||||||
if (body instanceof TimiResponse<?> timiResponse) {
|
if (body instanceof Response<?> Response) {
|
||||||
result = timiResponse;
|
result = Response;
|
||||||
} else {
|
} else {
|
||||||
result = new TimiResponse<>(TimiCode.SUCCESS, body);
|
result = new Response<>(ResultCode.SUCCESS, body);
|
||||||
}
|
}
|
||||||
if (30000 < result.getCode()) {
|
if (30000 < result.getCode()) {
|
||||||
log.warn("ID: {} Response -> Exception.{}.{}", TimiSpring.getSessionAttr(AOPLogInterceptor.REQUEST_ID), result.getCode(), result.getMessage());
|
log.warn("ID: {} Response -> Exception.{}.{}", TimiSpring.getSessionAttr(AOPLogInterceptor.REQUEST_ID), result.getCode(), result.getMessage());
|
||||||
}
|
}
|
||||||
|
if (StringHttpMessageConverter.class.isAssignableFrom(selectedConverterType)) {
|
||||||
|
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
|
||||||
|
try {
|
||||||
|
return objectMapper.writeValueAsString(result);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new IllegalStateException("统一响应序列化失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,364 @@
|
|||||||
|
package com.imyeyu.spring.util;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.imyeyu.java.TimiJava;
|
||||||
|
import com.imyeyu.java.bean.CallbackArgReturn;
|
||||||
|
import com.imyeyu.lang.bean.Language;
|
||||||
|
import com.imyeyu.lang.bean.MultilingualValue;
|
||||||
|
import com.imyeyu.spring.TimiSpring;
|
||||||
|
import com.imyeyu.spring.annotation.MultilingualField;
|
||||||
|
import com.imyeyu.utils.StringInterpolator;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.io.Reader;
|
||||||
|
import java.io.Writer;
|
||||||
|
import java.lang.reflect.Array;
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.lang.reflect.Modifier;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.time.temporal.TemporalAccessor;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.IdentityHashMap;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一回填响应对象中的多语言字段
|
||||||
|
*
|
||||||
|
* @author 夜雨
|
||||||
|
* @since 2026-07-17 00:00
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
public class MultilingualFieldBinder {
|
||||||
|
|
||||||
|
private static final StringInterpolator INTERPOLATOR = new StringInterpolator(StringInterpolator.SIMPLE_OBJ);
|
||||||
|
private static final Map<Class<?>, List<Field>> TRAVERSE_CACHE = new ConcurrentHashMap<>();
|
||||||
|
private static final Map<Class<?>, List<BindingField>> BINDING_CACHE = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
private final CallbackArgReturn<Collection<String>, ? extends Collection<? extends MultilingualValue>> callback;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建多语言字段回填器
|
||||||
|
*
|
||||||
|
* @param callback 根据多语言 ID 查询多语言值
|
||||||
|
*/
|
||||||
|
public MultilingualFieldBinder(CallbackArgReturn<Collection<String>, ? extends Collection<? extends MultilingualValue>> callback) {
|
||||||
|
this.callback = callback;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据当前请求语言回填对象中的多语言字段
|
||||||
|
*
|
||||||
|
* @param body 响应对象
|
||||||
|
*/
|
||||||
|
public void bind(Object body) {
|
||||||
|
if (body == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
LinkedHashSet<String> langIdSet = new LinkedHashSet<>();
|
||||||
|
// 第一遍只收集多语言 ID,避免递归回填时重复查询
|
||||||
|
collectLangId(body, new IdentityHashMap<>(), langIdSet);
|
||||||
|
if (langIdSet.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Map<String, MultilingualValue> multilingualMap = new LinkedHashMap<>();
|
||||||
|
for (MultilingualValue item : callback.handler(langIdSet)) {
|
||||||
|
multilingualMap.put(item.getId(), item);
|
||||||
|
}
|
||||||
|
// 第二遍执行字段回填,模板替换也在这一遍统一完成
|
||||||
|
fillValue(body, new IdentityHashMap<>(), multilingualMap, TimiSpring.getLanguage());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 递归扫描响应对象,提取所有待翻译字段依赖的多语言 ID
|
||||||
|
*
|
||||||
|
* @param current 当前对象
|
||||||
|
* @param visited 已访问对象,避免循环引用死递归
|
||||||
|
* @param langIdSet 收集到的多语言 ID
|
||||||
|
*/
|
||||||
|
private void collectLangId(Object current, IdentityHashMap<Object, Boolean> visited, LinkedHashSet<String> langIdSet) {
|
||||||
|
switch (current) {
|
||||||
|
case null -> {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case Collection<?> collection -> {
|
||||||
|
if (visited.put(current, Boolean.TRUE) != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (Object item : collection) {
|
||||||
|
collectLangId(item, visited, langIdSet);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case Map<?, ?> map -> {
|
||||||
|
if (visited.put(current, Boolean.TRUE) != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (Object item : map.values()) {
|
||||||
|
collectLangId(item, visited, langIdSet);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (current.getClass().isArray()) {
|
||||||
|
if (visited.put(current, Boolean.TRUE) != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int length = Array.getLength(current);
|
||||||
|
for (int i = 0; i < length; i++) {
|
||||||
|
collectLangId(Array.get(current, i), visited, langIdSet);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (isSimpleValueType(current.getClass())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (visited.put(current, Boolean.TRUE) != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (BindingField field : getBindingFields(current.getClass())) {
|
||||||
|
String langId = getStringValue(field.langIdField(), current);
|
||||||
|
if (TimiJava.isNotEmpty(langId)) {
|
||||||
|
langIdSet.add(langId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (Field field : getTraverseFields(current.getClass())) {
|
||||||
|
collectLangId(getFieldValue(field, current), visited, langIdSet);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 递归回填响应对象中的多语言展示字段
|
||||||
|
*
|
||||||
|
* @param current 当前对象
|
||||||
|
* @param visited 已访问对象,避免循环引用死递归
|
||||||
|
* @param multilingualMap 本次响应涉及的多语言缓存
|
||||||
|
* @param language 当前请求语言
|
||||||
|
*/
|
||||||
|
private void fillValue(Object current, IdentityHashMap<Object, Boolean> visited, Map<String, MultilingualValue> multilingualMap, Language.Enum language) {
|
||||||
|
if (current == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (current instanceof Collection<?> collection) {
|
||||||
|
if (visited.put(current, Boolean.TRUE) != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (Object item : collection) {
|
||||||
|
fillValue(item, visited, multilingualMap, language);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (current instanceof Map<?, ?> map) {
|
||||||
|
if (visited.put(current, Boolean.TRUE) != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (Object item : map.values()) {
|
||||||
|
fillValue(item, visited, multilingualMap, language);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (current.getClass().isArray()) {
|
||||||
|
if (visited.put(current, Boolean.TRUE) != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int length = Array.getLength(current);
|
||||||
|
for (int i = 0; i < length; i++) {
|
||||||
|
fillValue(Array.get(current, i), visited, multilingualMap, language);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (isSimpleValueType(current.getClass())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (visited.put(current, Boolean.TRUE) != null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (BindingField field : getBindingFields(current.getClass())) {
|
||||||
|
String langId = getStringValue(field.langIdField(), current);
|
||||||
|
if (TimiJava.isEmpty(langId)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
MultilingualValue multilingual = multilingualMap.get(langId);
|
||||||
|
if (multilingual == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String value = multilingual.getValue(language);
|
||||||
|
if (TimiJava.isEmpty(value)) {
|
||||||
|
value = multilingual.getValue(Language.Enum.zh_CN);
|
||||||
|
}
|
||||||
|
if (TimiJava.isEmpty(value)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Map<String, Object> argMap = getArgMapValue(field.argMapField(), current);
|
||||||
|
if (!argMap.isEmpty()) {
|
||||||
|
value = INTERPOLATOR.inject(value, argMap);
|
||||||
|
}
|
||||||
|
if (TimiJava.isEmpty(value)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
setFieldValue(field.targetField(), current, value);
|
||||||
|
}
|
||||||
|
for (Field field : getTraverseFields(current.getClass())) {
|
||||||
|
fillValue(getFieldValue(field, current), visited, multilingualMap, language);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<BindingField> getBindingFields(Class<?> clazz) {
|
||||||
|
return BINDING_CACHE.computeIfAbsent(clazz, key -> {
|
||||||
|
Map<String, Field> fieldMap = new LinkedHashMap<>();
|
||||||
|
List<Field> declaredFieldList = getAllFields(key);
|
||||||
|
for (Field field : declaredFieldList) {
|
||||||
|
fieldMap.put(field.getName(), field);
|
||||||
|
}
|
||||||
|
List<BindingField> result = new ArrayList<>();
|
||||||
|
for (Field field : declaredFieldList) {
|
||||||
|
MultilingualField annotation = field.getAnnotation(MultilingualField.class);
|
||||||
|
if (annotation == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Field langIdField = fieldMap.get(annotation.value());
|
||||||
|
if (langIdField == null) {
|
||||||
|
log.warn("MultilingualField 配置错误,类 {} 不存在字段 {}", key.getName(), annotation.value());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Field argMapField = null;
|
||||||
|
if (TimiJava.isNotEmpty(annotation.argMap())) {
|
||||||
|
argMapField = fieldMap.get(annotation.argMap());
|
||||||
|
if (argMapField == null) {
|
||||||
|
log.warn("MultilingualField 配置错误,类 {} 不存在字段 {}", key.getName(), annotation.argMap());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!Map.class.isAssignableFrom(argMapField.getType())) {
|
||||||
|
log.warn("MultilingualField 配置错误,类 {} 字段 {} 不是 Map", key.getName(), annotation.argMap());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.add(new BindingField(field, langIdField, argMapField));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成需要继续向下遍历的字段列表
|
||||||
|
*
|
||||||
|
* @param clazz 目标类型
|
||||||
|
* @return 可递归字段列表
|
||||||
|
*/
|
||||||
|
private List<Field> getTraverseFields(Class<?> clazz) {
|
||||||
|
return TRAVERSE_CACHE.computeIfAbsent(clazz, key -> {
|
||||||
|
List<Field> result = new ArrayList<>();
|
||||||
|
for (Field field : getAllFields(key)) {
|
||||||
|
if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (field.getType().isArray() || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())) {
|
||||||
|
field.setAccessible(true);
|
||||||
|
result.add(field);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (isSimpleValueType(field.getType())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
field.setAccessible(true);
|
||||||
|
result.add(field);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Field> getAllFields(Class<?> clazz) {
|
||||||
|
List<Field> result = new ArrayList<>();
|
||||||
|
Class<?> current = clazz;
|
||||||
|
while (current != null && current != Object.class) {
|
||||||
|
for (Field field : current.getDeclaredFields()) {
|
||||||
|
if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
field.setAccessible(true);
|
||||||
|
result.add(field);
|
||||||
|
}
|
||||||
|
current = current.getSuperclass();
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 仅接受字符串类型的 langId 字段
|
||||||
|
*
|
||||||
|
* @param field 字段
|
||||||
|
* @param target 对象
|
||||||
|
* @return 多语言 ID
|
||||||
|
*/
|
||||||
|
private String getStringValue(Field field, Object target) {
|
||||||
|
Object value = getFieldValue(field, target);
|
||||||
|
if (value instanceof String string) {
|
||||||
|
return string;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 仅读取 Map 类型模板参数字段,未配置时返回空 Map
|
||||||
|
*
|
||||||
|
* @param field 字段
|
||||||
|
* @param target 对象
|
||||||
|
* @return 模板参数
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> getArgMapValue(Field field, Object target) {
|
||||||
|
if (field == null) {
|
||||||
|
return Map.of();
|
||||||
|
}
|
||||||
|
Object value = getFieldValue(field, target);
|
||||||
|
if (value instanceof Map<?, ?> map) {
|
||||||
|
return (Map<String, Object>) map;
|
||||||
|
}
|
||||||
|
return Map.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object getFieldValue(Field field, Object target) {
|
||||||
|
try {
|
||||||
|
return field.get(target);
|
||||||
|
} catch (IllegalAccessException e) {
|
||||||
|
throw new IllegalStateException("读取字段失败: %s#%s".formatted(target.getClass().getName(), field.getName()), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setFieldValue(Field field, Object target, Object value) {
|
||||||
|
try {
|
||||||
|
field.set(target, value);
|
||||||
|
} catch (IllegalAccessException e) {
|
||||||
|
throw new IllegalStateException("写入字段失败: %s#%s".formatted(target.getClass().getName(), field.getName()), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isSimpleValueType(Class<?> clazz) {
|
||||||
|
if (clazz.isPrimitive() || clazz.isEnum() || clazz.isAnnotation()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (CharSequence.class.isAssignableFrom(clazz) || Number.class.isAssignableFrom(clazz) || Boolean.class == clazz || Character.class == clazz || UUID.class == clazz || TemporalAccessor.class.isAssignableFrom(clazz) || Class.class == clazz || JsonNode.class.isAssignableFrom(clazz) || File.class.isAssignableFrom(clazz) || Path.class.isAssignableFrom(clazz) || InputStream.class.isAssignableFrom(clazz) || OutputStream.class.isAssignableFrom(clazz) || Reader.class.isAssignableFrom(clazz) || Writer.class.isAssignableFrom(clazz)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
Package currentPackage = clazz.getPackage();
|
||||||
|
if (currentPackage == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String packageName = currentPackage.getName();
|
||||||
|
return packageName.startsWith("java.") || packageName.startsWith("javax.") || packageName.startsWith("jakarta.") || packageName.startsWith("sun.") || packageName.startsWith("com.fasterxml.jackson.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private record BindingField(Field targetField, Field langIdField, Field argMapField) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package com.imyeyu.spring.util;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.beans.factory.ObjectProvider;
|
||||||
|
import org.springframework.core.MethodParameter;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.http.converter.HttpMessageConverter;
|
||||||
|
import org.springframework.http.server.ServerHttpRequest;
|
||||||
|
import org.springframework.http.server.ServerHttpResponse;
|
||||||
|
import org.springframework.lang.NonNull;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一处理响应中的多语言字段回填
|
||||||
|
*
|
||||||
|
* @author 夜雨
|
||||||
|
* @since 2026-07-17 00:00
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@RestControllerAdvice
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class MultilingualResponseBodyAdvice implements ResponseBodyAdvice<Object> {
|
||||||
|
|
||||||
|
private final ObjectProvider<MultilingualFieldBinder> multilingualFieldBinder;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean supports(@NonNull MethodParameter returnType, @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object beforeBodyWrite(
|
||||||
|
Object body,
|
||||||
|
@NonNull MethodParameter returnType,
|
||||||
|
@NonNull MediaType selectedContentType,
|
||||||
|
@NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
|
||||||
|
@NonNull ServerHttpRequest request,
|
||||||
|
@NonNull ServerHttpResponse response
|
||||||
|
) {
|
||||||
|
MultilingualFieldBinder binder = multilingualFieldBinder.getIfAvailable();
|
||||||
|
if (binder != null) {
|
||||||
|
binder.bind(body);
|
||||||
|
}
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
package com.imyeyu.spring.util;
|
package com.imyeyu.spring.util;
|
||||||
|
|
||||||
import com.imyeyu.java.bean.timi.TimiException;
|
import com.imyeyu.java.bean.ActionException;
|
||||||
import com.imyeyu.spring.bean.Logic;
|
import com.imyeyu.spring.bean.Logic;
|
||||||
import com.imyeyu.spring.mapper.BaseMapper;
|
import com.imyeyu.spring.mapper.BaseMapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
@@ -25,7 +25,7 @@ public class RawSQLProvider extends SQLProvider {
|
|||||||
@Override
|
@Override
|
||||||
public String select(ProviderContext context, Object id) {
|
public String select(ProviderContext context, Object id) {
|
||||||
EntityMeta meta = getEntityMeta(context);
|
EntityMeta meta = getEntityMeta(context);
|
||||||
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||||
return "SELECT %s FROM `%s` WHERE `%s` = #{%s}".formatted(meta.selectAllClause, meta.table, meta.idFieldColumn.columnName, id) + " LIMIT 1";
|
return "SELECT %s FROM `%s` WHERE `%s` = #{%s}".formatted(meta.selectAllClause, meta.table, meta.idFieldColumn.columnName, id) + " LIMIT 1";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
package com.imyeyu.spring.util;
|
package com.imyeyu.spring.util;
|
||||||
|
|
||||||
import com.imyeyu.java.TimiJava;
|
import com.imyeyu.java.TimiJava;
|
||||||
import com.imyeyu.java.bean.timi.TimiException;
|
import com.imyeyu.java.bean.ActionException;
|
||||||
import com.imyeyu.spring.config.AbstractRedisConfig;
|
import com.imyeyu.spring.config.AbstractRedisConfig;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Getter;
|
||||||
import org.springframework.data.redis.connection.RedisConnection;
|
import org.springframework.data.redis.connection.RedisConnection;
|
||||||
import org.springframework.data.redis.core.Cursor;
|
import org.springframework.data.redis.core.Cursor;
|
||||||
import org.springframework.data.redis.core.RedisTemplate;
|
import org.springframework.data.redis.core.RedisTemplate;
|
||||||
@@ -31,7 +32,10 @@ import java.util.function.Consumer;
|
|||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public class Redis<K, V> {
|
public class Redis<K, V> {
|
||||||
|
|
||||||
|
@Getter
|
||||||
private RedisTemplate<K, V> redis;
|
private RedisTemplate<K, V> redis;
|
||||||
|
|
||||||
|
@Getter
|
||||||
private RedisSerializer<K> serializer;
|
private RedisSerializer<K> serializer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -213,7 +217,7 @@ public class Redis<K, V> {
|
|||||||
* 获取所有值
|
* 获取所有值
|
||||||
*
|
*
|
||||||
* @return 所有值
|
* @return 所有值
|
||||||
* @throws TimiException 异常
|
* @throws ActionException 异常
|
||||||
*/
|
*/
|
||||||
public List<V> values() {
|
public List<V> values() {
|
||||||
List<V> r = new ArrayList<>();
|
List<V> r = new ArrayList<>();
|
||||||
|
|||||||
Reference in New Issue
Block a user