add BaseMapper.updateSelective
This commit is contained in:
@ -93,6 +93,9 @@ public interface BaseMapper<T, P> {
|
||||
@UpdateProvider(type = SQLProvider.class, method = "update")
|
||||
void update(T t);
|
||||
|
||||
@UpdateProvider(type = SQLProvider.class, method = "updateSelective")
|
||||
void updateSelective(T t);
|
||||
|
||||
/**
|
||||
* 软删除
|
||||
*
|
||||
|
||||
@ -9,6 +9,7 @@ import com.imyeyu.spring.annotation.table.Column;
|
||||
import com.imyeyu.spring.annotation.table.Id;
|
||||
import com.imyeyu.spring.annotation.table.Table;
|
||||
import com.imyeyu.spring.annotation.table.Transient;
|
||||
import com.imyeyu.spring.entity.BaseEntity;
|
||||
import com.imyeyu.spring.entity.Creatable;
|
||||
import com.imyeyu.spring.entity.Deletable;
|
||||
import com.imyeyu.spring.entity.Destroyable;
|
||||
@ -189,6 +190,42 @@ public class SQLProvider {
|
||||
return "UPDATE `%s` SET %s WHERE `%s` = #{%s}".formatted(meta.table, setClause, meta.idFieldColumn.columnName, meta.idFieldColumn.fieldName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 ID 更新,选择性更新非空属性,需要实体实现 {@link Updatable}
|
||||
*
|
||||
* @param entity 实体
|
||||
* @return SQL
|
||||
*/
|
||||
public String updateSelective(Object entity) {
|
||||
EntityMeta meta = getEntityMeta(entity.getClass());
|
||||
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
|
||||
TimiException.required(meta.canUpdate, "not allow update for %s".formatted(meta.entityClass));
|
||||
|
||||
if (entity instanceof BaseEntity baseEntity) {
|
||||
baseEntity.setCreatedAt(null);
|
||||
baseEntity.setDeletedAt(null);
|
||||
}
|
||||
String setClause = meta.fieldColumnList.stream()
|
||||
.filter(fc -> {
|
||||
if (fc.isId) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return Ref.getFieldValue(entity, fc.field, Object.class) != null;
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
})
|
||||
.map(fc -> {
|
||||
if (entity instanceof Updatable updatableEntity) {
|
||||
updatableEntity.setUpdatedAt(Time.now());
|
||||
}
|
||||
return "`%s` = #{%s}".formatted(fc.columnName, fc.fieldName);
|
||||
})
|
||||
.collect(Collectors.joining(", "));
|
||||
return "UPDATE `%s` SET %s WHERE `%s` = #{%s}".formatted(meta.table, setClause, meta.idFieldColumn.columnName, meta.idFieldColumn.fieldName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 ID 软删除,需要实体实现 {@link Deletable}
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user