260610_01_ENH: 컬럼명으로 entity 접근하는 유틸 추가
This commit is contained in:
@@ -4,7 +4,7 @@ plugins {
|
||||
}
|
||||
|
||||
// 버전 변경은 여기서
|
||||
def commonVer = "beta.1.1.23"
|
||||
def commonVer = "beta.1.1.24"
|
||||
|
||||
group = 'com.kri.common'
|
||||
version = commonVer
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
package com.kri.common.feature.jpa;
|
||||
|
||||
import com.kri.common.feature.web.BusinessException;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.EmbeddedId;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public final class EntityColumnAccessor<T> {
|
||||
|
||||
private static final ConcurrentHashMap<Class<?>, Map<String, ColumnMeta>> CACHE =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
private final Class<T> entityType;
|
||||
private final Map<String, ColumnMeta> columns;
|
||||
|
||||
private EntityColumnAccessor(Class<T> entityType) {
|
||||
this.entityType = entityType;
|
||||
this.columns = CACHE.computeIfAbsent(entityType, EntityColumnAccessor::createColumnMap);
|
||||
}
|
||||
|
||||
public static <T> EntityColumnAccessor<T> of(Class<T> entityType) {
|
||||
return new EntityColumnAccessor<>(entityType);
|
||||
}
|
||||
|
||||
public Object get(T entity, String columnName) {
|
||||
validateEntity(entity);
|
||||
ColumnMeta meta = getColumnMeta(columnName);
|
||||
Object target = getTarget(entity, meta, false);
|
||||
if (target == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return meta.field().get(target);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw BusinessException.internalError(
|
||||
"ENTITY_COLUMN_ACCESS_FAILED",
|
||||
"엔티티 컬럼 값을 읽을 수 없습니다.")
|
||||
.with("entityType", entityType.getName())
|
||||
.with("columnName", columnName);
|
||||
}
|
||||
}
|
||||
|
||||
public <V> V get(T entity, String columnName, Class<V> valueType) {
|
||||
Object value = get(entity, columnName);
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (!valueType.isInstance(value)) {
|
||||
throw BusinessException.validationError(
|
||||
"ENTITY_COLUMN_TYPE_MISMATCH",
|
||||
"엔티티 컬럼 값 타입이 요청 타입과 일치하지 않습니다.")
|
||||
.with("entityType", entityType.getName())
|
||||
.with("columnName", columnName)
|
||||
.with("actualType", value.getClass().getName())
|
||||
.with("requestedType", valueType.getName());
|
||||
}
|
||||
return valueType.cast(value);
|
||||
}
|
||||
|
||||
public void set(T entity, String columnName, Object value) {
|
||||
setValue(entity, columnName, value, WriteMode.ANY);
|
||||
}
|
||||
|
||||
public void setForInsert(T entity, String columnName, Object value) {
|
||||
setValue(entity, columnName, value, WriteMode.INSERT);
|
||||
}
|
||||
|
||||
public void setForUpdate(T entity, String columnName, Object value) {
|
||||
setValue(entity, columnName, value, WriteMode.UPDATE);
|
||||
}
|
||||
|
||||
private void setValue(T entity, String columnName, Object value, WriteMode writeMode) {
|
||||
validateEntity(entity);
|
||||
ColumnMeta meta = getColumnMeta(columnName);
|
||||
validateWritable(meta, columnName, writeMode);
|
||||
validateFinal(meta, columnName);
|
||||
|
||||
Object converted = convertValue(value, meta.field().getType(), columnName);
|
||||
Object target = getTarget(entity, meta, true);
|
||||
|
||||
try {
|
||||
meta.field().set(target, converted);
|
||||
} catch (IllegalAccessException e) {
|
||||
throw BusinessException.internalError(
|
||||
"ENTITY_COLUMN_ACCESS_FAILED",
|
||||
"엔티티 컬럼 값을 설정할 수 없습니다.")
|
||||
.with("entityType", entityType.getName())
|
||||
.with("columnName", columnName);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateEntity(T entity) {
|
||||
if (entity == null) {
|
||||
throw BusinessException.badRequest(
|
||||
"ENTITY_REQUIRED",
|
||||
"엔티티 객체가 필요합니다.");
|
||||
}
|
||||
}
|
||||
|
||||
private ColumnMeta getColumnMeta(String columnName) {
|
||||
if (columnName == null || columnName.isBlank()) {
|
||||
throw BusinessException.badRequest(
|
||||
"COLUMN_NAME_REQUIRED",
|
||||
"컬럼명이 필요합니다.");
|
||||
}
|
||||
|
||||
ColumnMeta meta = columns.get(normalizeColumnName(columnName));
|
||||
if (meta == null) {
|
||||
throw BusinessException.notFound(
|
||||
"ENTITY_COLUMN_NOT_FOUND",
|
||||
"엔티티에 해당 컬럼이 없습니다.")
|
||||
.with("entityType", entityType.getName())
|
||||
.with("columnName", columnName);
|
||||
}
|
||||
return meta;
|
||||
}
|
||||
|
||||
private Object getTarget(T entity, ColumnMeta meta, boolean createEmbeddedId) {
|
||||
if (meta.embeddedIdField() == null) {
|
||||
return entity;
|
||||
}
|
||||
|
||||
try {
|
||||
Object embeddedId = meta.embeddedIdField().get(entity);
|
||||
if (embeddedId == null && createEmbeddedId) {
|
||||
embeddedId = createEmbeddedId(meta.embeddedIdField().getType(), meta);
|
||||
meta.embeddedIdField().set(entity, embeddedId);
|
||||
}
|
||||
return embeddedId;
|
||||
} catch (IllegalAccessException e) {
|
||||
throw BusinessException.internalError(
|
||||
"ENTITY_EMBEDDED_ID_ACCESS_FAILED",
|
||||
"엔티티 EmbeddedId에 접근할 수 없습니다.")
|
||||
.with("entityType", entityType.getName())
|
||||
.with("embeddedIdField", meta.embeddedIdField().getName());
|
||||
}
|
||||
}
|
||||
|
||||
private Object createEmbeddedId(Class<?> embeddedIdType, ColumnMeta meta) {
|
||||
try {
|
||||
Constructor<?> constructor = embeddedIdType.getDeclaredConstructor();
|
||||
constructor.setAccessible(true);
|
||||
return constructor.newInstance();
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw BusinessException.internalError(
|
||||
"ENTITY_EMBEDDED_ID_CREATE_FAILED",
|
||||
"엔티티 EmbeddedId 객체를 생성할 수 없습니다.")
|
||||
.with("entityType", entityType.getName())
|
||||
.with("embeddedIdType", embeddedIdType.getName())
|
||||
.with("columnName", meta.columnName());
|
||||
}
|
||||
}
|
||||
|
||||
private void validateWritable(ColumnMeta meta, String columnName, WriteMode writeMode) {
|
||||
if (writeMode == WriteMode.INSERT && !meta.insertable()) {
|
||||
throw BusinessException.validationError(
|
||||
"ENTITY_COLUMN_NOT_INSERTABLE",
|
||||
"insertable=false 컬럼은 insert 값으로 설정할 수 없습니다.")
|
||||
.with("entityType", entityType.getName())
|
||||
.with("columnName", columnName);
|
||||
}
|
||||
if (writeMode == WriteMode.UPDATE && !meta.updatable()) {
|
||||
throw BusinessException.validationError(
|
||||
"ENTITY_COLUMN_NOT_UPDATABLE",
|
||||
"updatable=false 컬럼은 update 값으로 설정할 수 없습니다.")
|
||||
.with("entityType", entityType.getName())
|
||||
.with("columnName", columnName);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateFinal(ColumnMeta meta, String columnName) {
|
||||
if (Modifier.isFinal(meta.field().getModifiers())) {
|
||||
throw BusinessException.validationError(
|
||||
"ENTITY_COLUMN_FINAL_FIELD",
|
||||
"final 필드는 값을 설정할 수 없습니다.")
|
||||
.with("entityType", entityType.getName())
|
||||
.with("columnName", columnName)
|
||||
.with("fieldName", meta.field().getName());
|
||||
}
|
||||
}
|
||||
|
||||
private Object convertValue(Object value, Class<?> targetType, String columnName) {
|
||||
if (value == null) {
|
||||
if (targetType.isPrimitive()) {
|
||||
throw BusinessException.validationError(
|
||||
"ENTITY_COLUMN_NULL_PRIMITIVE",
|
||||
"primitive 타입 컬럼에는 null을 설정할 수 없습니다.")
|
||||
.with("entityType", entityType.getName())
|
||||
.with("columnName", columnName)
|
||||
.with("targetType", targetType.getName());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Class<?> boxedType = boxType(targetType);
|
||||
if (boxedType.isInstance(value)) {
|
||||
return value;
|
||||
}
|
||||
|
||||
String text = value.toString();
|
||||
if (text.isBlank()) {
|
||||
return convertBlankValue(boxedType, columnName);
|
||||
}
|
||||
|
||||
try {
|
||||
return convertText(text, boxedType);
|
||||
} catch (RuntimeException e) {
|
||||
throw BusinessException.validationError(
|
||||
"ENTITY_COLUMN_CONVERT_FAILED",
|
||||
"엔티티 컬럼 값 타입 변환에 실패했습니다.")
|
||||
.with("entityType", entityType.getName())
|
||||
.with("columnName", columnName)
|
||||
.with("value", value)
|
||||
.with("targetType", targetType.getName());
|
||||
}
|
||||
}
|
||||
|
||||
private Object convertBlankValue(Class<?> targetType, String columnName) {
|
||||
if (targetType == String.class) {
|
||||
return "";
|
||||
}
|
||||
throw BusinessException.validationError(
|
||||
"ENTITY_COLUMN_CONVERT_FAILED",
|
||||
"빈 문자열은 대상 타입으로 변환할 수 없습니다.")
|
||||
.with("entityType", entityType.getName())
|
||||
.with("columnName", columnName)
|
||||
.with("targetType", targetType.getName());
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private Object convertText(String text, Class<?> targetType) {
|
||||
if (targetType == String.class) {
|
||||
return text;
|
||||
}
|
||||
if (targetType == Integer.class) {
|
||||
return Integer.valueOf(text);
|
||||
}
|
||||
if (targetType == Long.class) {
|
||||
return Long.valueOf(text);
|
||||
}
|
||||
if (targetType == Short.class) {
|
||||
return Short.valueOf(text);
|
||||
}
|
||||
if (targetType == Byte.class) {
|
||||
return Byte.valueOf(text);
|
||||
}
|
||||
if (targetType == Double.class) {
|
||||
return Double.valueOf(text);
|
||||
}
|
||||
if (targetType == Float.class) {
|
||||
return Float.valueOf(text);
|
||||
}
|
||||
if (targetType == BigDecimal.class) {
|
||||
return new BigDecimal(text);
|
||||
}
|
||||
if (targetType == BigInteger.class) {
|
||||
return new BigInteger(text);
|
||||
}
|
||||
if (targetType == Boolean.class) {
|
||||
return convertBoolean(text);
|
||||
}
|
||||
if (targetType == LocalDate.class) {
|
||||
return LocalDate.parse(text);
|
||||
}
|
||||
if (targetType == LocalDateTime.class) {
|
||||
return LocalDateTime.parse(text);
|
||||
}
|
||||
if (targetType == LocalTime.class) {
|
||||
return LocalTime.parse(text);
|
||||
}
|
||||
if (targetType.isEnum()) {
|
||||
return Enum.valueOf((Class<? extends Enum>) targetType, text);
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Unsupported target type: " + targetType.getName());
|
||||
}
|
||||
|
||||
private Boolean convertBoolean(String text) {
|
||||
return switch (text.trim().toLowerCase(Locale.ROOT)) {
|
||||
case "true", "t", "yes", "y", "1" -> true;
|
||||
case "false", "f", "no", "n", "0" -> false;
|
||||
default -> throw new IllegalArgumentException("Unsupported boolean value: " + text);
|
||||
};
|
||||
}
|
||||
|
||||
private Class<?> boxType(Class<?> type) {
|
||||
if (!type.isPrimitive()) {
|
||||
return type;
|
||||
}
|
||||
if (type == int.class) {
|
||||
return Integer.class;
|
||||
}
|
||||
if (type == long.class) {
|
||||
return Long.class;
|
||||
}
|
||||
if (type == short.class) {
|
||||
return Short.class;
|
||||
}
|
||||
if (type == byte.class) {
|
||||
return Byte.class;
|
||||
}
|
||||
if (type == double.class) {
|
||||
return Double.class;
|
||||
}
|
||||
if (type == float.class) {
|
||||
return Float.class;
|
||||
}
|
||||
if (type == boolean.class) {
|
||||
return Boolean.class;
|
||||
}
|
||||
if (type == char.class) {
|
||||
return Character.class;
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
private static Map<String, ColumnMeta> createColumnMap(Class<?> entityType) {
|
||||
Map<String, ColumnMeta> columns = new HashMap<>();
|
||||
for (Field field : getAllFields(entityType)) {
|
||||
field.setAccessible(true);
|
||||
if (field.isAnnotationPresent(EmbeddedId.class)) {
|
||||
addEmbeddedIdColumns(entityType, columns, field);
|
||||
continue;
|
||||
}
|
||||
|
||||
Column column = field.getAnnotation(Column.class);
|
||||
if (column != null) {
|
||||
addColumn(entityType, columns, null, field, column);
|
||||
}
|
||||
}
|
||||
return Map.copyOf(columns);
|
||||
}
|
||||
|
||||
private static void addEmbeddedIdColumns(
|
||||
Class<?> entityType,
|
||||
Map<String, ColumnMeta> columns,
|
||||
Field embeddedIdField
|
||||
) {
|
||||
for (Field field : getAllFields(embeddedIdField.getType())) {
|
||||
field.setAccessible(true);
|
||||
Column column = field.getAnnotation(Column.class);
|
||||
if (column != null) {
|
||||
addColumn(entityType, columns, embeddedIdField, field, column);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void addColumn(
|
||||
Class<?> entityType,
|
||||
Map<String, ColumnMeta> columns,
|
||||
Field embeddedIdField,
|
||||
Field field,
|
||||
Column column
|
||||
) {
|
||||
String columnName = column.name();
|
||||
if (columnName == null || columnName.isBlank()) {
|
||||
columnName = field.getName();
|
||||
}
|
||||
|
||||
String key = normalizeColumnName(columnName);
|
||||
ColumnMeta previous = columns.putIfAbsent(
|
||||
key,
|
||||
new ColumnMeta(
|
||||
columnName,
|
||||
embeddedIdField,
|
||||
field,
|
||||
column.insertable(),
|
||||
column.updatable()
|
||||
)
|
||||
);
|
||||
if (previous != null) {
|
||||
throw BusinessException.internalError(
|
||||
"ENTITY_COLUMN_DUPLICATED",
|
||||
"엔티티 컬럼 매핑이 중복되었습니다.")
|
||||
.with("entityType", entityType.getName())
|
||||
.with("columnName", columnName)
|
||||
.with("fieldName", field.getName())
|
||||
.with("previousFieldName", previous.field().getName());
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Field> getAllFields(Class<?> type) {
|
||||
List<Field> fields = new java.util.ArrayList<>();
|
||||
Class<?> current = type;
|
||||
while (current != null && current != Object.class) {
|
||||
fields.addAll(List.of(current.getDeclaredFields()));
|
||||
current = current.getSuperclass();
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
private static String normalizeColumnName(String columnName) {
|
||||
return columnName.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private enum WriteMode {
|
||||
ANY,
|
||||
INSERT,
|
||||
UPDATE
|
||||
}
|
||||
|
||||
private record ColumnMeta(
|
||||
String columnName,
|
||||
Field embeddedIdField,
|
||||
Field field,
|
||||
boolean insertable,
|
||||
boolean updatable
|
||||
) {
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user