mybatis-mapper / mapper

MyBatis Mapper
https://mapper.mybatis.io
Apache License 2.0
325 stars 47 forks source link

当主键 id 为空字符串时自动生成主键不生效,能否处理下 #99

Closed oiltea closed 1 month ago

abel533 commented 2 months ago

可以重写该方法,例如:

public class CustomEntityProvider {

  /**
   * 保存实体中不为空的字段
   *
   * @param providerContext 上下文
   * @return cacheKey
   */
  public static String insertSelective(ProviderContext providerContext) {
    return SqlScript.caching(providerContext, new SqlScript() {
      @Override
      public String getSql(EntityTable entity) {
        return "INSERT INTO " + entity.tableName()
            + trimSuffixOverrides("(", ")", ",", () ->
            entity.insertColumns().stream().map(column ->
                ifTest(column.notEmptyTest(), () -> column.column() + ",")
            ).collect(Collectors.joining(LF)))
            + trimSuffixOverrides(" VALUES (", ")", ",", () ->
            entity.insertColumns().stream().map(column ->
                ifTest(column.notEmptyTest(), () -> column.variables() + ",")
            ).collect(Collectors.joining(LF)));
      }
    });
  }
}

notNullTest 改为 notEmptyTest

然后在自定义的基类Mapper中覆盖定义即可:

public interface CustomMapper<T, I extends Serializable> extends BaseMapper<T, I> {

  /**
   * 保存实体中不为空的字段
   *
   * @param entity 实体类
   * @return 1成功,0失败
   */
  @Lang(Caching.class)
  @InsertProvider(type = CustomEntityProvider.class, method = "insertSelective")
  int insertSelective(T entity);
}

有其他个性化需求可以参考这种方式进行修改。