1.2K Star 5.7K Fork 2.5K

闲.大赋 / springboot-plus

 / 详情

数据库主键不自增不能自己填值

Backlog
Opened this issue  
2021-08-11 16:14

数据库主键不是自增的,自己填值不能插入数据吗,一定要主键自增才行的吗

Comments (4)

soulmate created任务
soulmate set related repository to 闲.大赋/springboot-plus
Expand operation logs

目前没有这样功能,为啥需要自己填值,如果需要,可以改成@AssingId

好的,@AssingID好像就能满足我的需求了,感谢

用的是tk.mapper 还是mapper-plus. 如果是tk.mapper

BaseInsertProvider.java
import org.apache.ibatis.mapping.MappedStatement;
import tk.mybatis.mapper.MapperException;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.*;
import java.util.Set;

/**

  • BaseInsertProvider实现类,基础方法实现类

*/
public class BaseInsertProvider extends MapperTemplate {

public BaseInsertProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
    super(mapperClass, mapperHelper);
}

public String BaseInsert(MappedStatement ms) {
    Class<?> entityClass = getEntityClass(ms);
    StringBuilder sql = new StringBuilder();
    //获取全部列
    Set<EntityColumn> columnList = EntityHelper.getColumns(entityClass);
    EntityColumn logicDeleteColumn = SqlHelper.getLogicDeleteColumn(entityClass);
    processKey(sql, entityClass, ms, columnList);
    sql.append(SqlHelper.insertIntoTable(entityClass, tableName(entityClass)));
    sql.append(SqlHelper.insertColumns(entityClass, false, false, false));
    sql.append("<trim prefix=\"VALUES(\" suffix=\")\" suffixOverrides=\",\">");
    for (EntityColumn column : columnList) {
        if (!column.isInsertable()) {
            continue;
        }
        if (logicDeleteColumn != null && logicDeleteColumn == column) {
            sql.append(SqlHelper.getLogicDeletedValue(column, false)).append(",");
            continue;
        }
        //优先使用传入的属性值,当原属性property!=null时,用原属性
        //自增的情况下,如果默认有值,就会备份到property_cache中,所以这里需要先判断备份的值是否存在
        if (column.isIdentity()) {
            sql.append(SqlHelper.getIfCacheNotNull(column, column.getColumnHolder(null, "_cache", ",")));
        } else {
            //其他情况值仍然存在原property中
            sql.append(SqlHelper.getIfNotNull(column, column.getColumnHolder(null, null, ","), isNotEmpty()));
        }
        //当属性为null时,如果存在主键策略,会自动获取值,如果不存在,则使用null
        if (column.isIdentity()) {
            sql.append(SqlHelper.getIfCacheIsNull(column, column.getColumnHolder() + ","));
        } else {
            //当null的时候,如果不指定jdbcType,oracle可能会报异常,指定VARCHAR不影响其他
            sql.append(SqlHelper.getIfIsNull(column, column.getColumnHolder(null, null, ","), isNotEmpty()));
        }
    }
    sql.append("</trim>");
    return sql.toString();
}

public String BaseInsertSelective(MappedStatement ms) {
    Class<?> entityClass = getEntityClass(ms);
    StringBuilder sql = new StringBuilder();
    //获取全部列
    Set<EntityColumn> columnList = EntityHelper.getColumns(entityClass);
    EntityColumn logicDeleteColumn = SqlHelper.getLogicDeleteColumn(entityClass);
    processKey(sql, entityClass, ms, columnList);
    sql.append(SqlHelper.insertIntoTable(entityClass, tableName(entityClass)));
    sql.append("<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">");
    for (EntityColumn column : columnList) {
        if (!column.isInsertable()) {
            continue;
        }
        if (column.isIdentity()) {
            sql.append(column.getColumn()).append(",");
        } else {
            if (logicDeleteColumn != null && logicDeleteColumn == column) {
                sql.append(column.getColumn()).append(",");
                continue;
            }
            sql.append(SqlHelper.getIfNotNull(column, column.getColumn() + ",", isNotEmpty()));
        }
    }
    sql.append("</trim>");

    sql.append("<trim prefix=\"VALUES(\" suffix=\")\" suffixOverrides=\",\">");
    for (EntityColumn column : columnList) {
        if (!column.isInsertable()) {
            continue;
        }
        if (logicDeleteColumn != null && logicDeleteColumn == column) {
            sql.append(SqlHelper.getLogicDeletedValue(column, false)).append(",");
            continue;
        }
        //优先使用传入的属性值,当原属性property!=null时,用原属性
        //自增的情况下,如果默认有值,就会备份到property_cache中,所以这里需要先判断备份的值是否存在
        if (column.isIdentity()) {
            sql.append(SqlHelper.getIfCacheNotNull(column, column.getColumnHolder(null, "_cache", ",")));
        } else {
            //其他情况值仍然存在原property中
            sql.append(SqlHelper.getIfNotNull(column, column.getColumnHolder(null, null, ","), isNotEmpty()));
        }
        //当属性为null时,如果存在主键策略,会自动获取值,如果不存在,则使用null
        //序列的情况
        if (column.isIdentity()) {
            sql.append(SqlHelper.getIfCacheIsNull(column, column.getColumnHolder() + ","));
        }
    }
    sql.append("</trim>");
    return sql.toString();
}

private void processKey(StringBuilder sql, Class<?> entityClass, MappedStatement ms, Set<EntityColumn> columnList){
    //Identity列只能有一个
    Boolean hasIdentityKey = false;
    //先处理cache或bind节点
    for (EntityColumn column : columnList) {
        if (column.isIdentity()) {
            //这种情况下,如果原先的字段有值,需要先缓存起来,否则就一定会使用自动增长
            //这是一个bind节点
            sql.append(SqlHelper.getBindCache(column));
            //如果是Identity列,就需要插入selectKey
            //如果已经存在Identity列,抛出异常
            if (hasIdentityKey) {
                //jdbc类型只需要添加一次
                if (column.getGenerator() != null && "JDBC".equals(column.getGenerator())) {
                    continue;
                }
                throw new MapperException(ms.getId() + "对应的实体类" + entityClass.getCanonicalName() + "中包含多个MySql的自动增长列,最多只能有一个!");
            }
            //插入selectKey
            SelectKeyHelper.newSelectKeyMappedStatement(ms, column, entityClass, isBEFORE(), getIDENTITY(column));
            hasIdentityKey = true;
        } else if(column.getGenIdClass() != null){
            sql.append("<bind name=\"").append(column.getColumn()).append("GenIdBind\" value=\"@tk.mybatis.mapper.genid.GenIdUtil@genId(");
            sql.append("_parameter").append(", '").append(column.getProperty()).append("'");
            sql.append(", @").append(column.getGenIdClass().getCanonicalName()).append("@class");
            sql.append(", '").append(tableName(entityClass)).append("'");
            sql.append(", '").append(column.getColumn()).append("')");
            sql.append("\"/>");
        }

    }
}

}

BaseInsertMapper.java
@tk.mybatis.mapper.annotation.RegisterMapper
public interface BaseInsertMapper {

 /**
 * 保存一个实体,null的属性也会保存,不会使用数据库默认值
 *
 * @param record
 * @return
 */
@Options(useGeneratedKeys = true)
@InsertProvider(type = BaseInsertProvider.class, method = "dynamicSQL")
int BaseInsert(T record);

}

BaseInsertSelectiveMapper.java
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Options;
@tk.mybatis.mapper.annotation.RegisterMapper
public interface BaseInsertSelectiveMapper {

 /**
 * 保存一个实体,null的属性不会保存,会使用数据库默认值
 *
 * @param record
 * @return
 */
@Options(useGeneratedKeys = true)
@InsertProvider(type = BaseInsertProvider.class, method = "dynamicSQL")
int BaseInsertSelective(T record);

}

在自己引用的myMapper 中添加baseInsetMapper 和 baseInsetSelectiveMapper
import org.apache.logging.log4j.Marker;
import com.xx.utils.mapper.BaseInsertMapper;
import com.xx.utils.mapper.BaseInsertSelectiveMapper;
import tk.mybatis.mapper.common.ExampleMapper;
import tk.mybatis.mapper.common.MySqlMapper;
import tk.mybatis.mapper.common.RowBoundsMapper;
import tk.mybatis.mapper.common.SqlServerMapper;
import tk.mybatis.mapper.common.base.BaseDeleteMapper;
import tk.mybatis.mapper.common.base.BaseSelectMapper;
import tk.mybatis.mapper.common.base.BaseUpdateMapper;
/**

  • 继承自己的MyMapper
  • @Author
  • @since_2013 2015-09-06 21:53
    */
    public interface MyMapper extends
    /Mapper,/
    BaseInsertSelectiveMapper,
    BaseInsertMapper,
    MySqlMapper,
    ExampleMapper,
    RowBoundsMapper,
    BaseSelectMapper,
    BaseUpdateMapper,
    BaseDeleteMapper,
    SqlServerMapper,
    Marker{
    //TODO
    //FIXME 特别注意,该接口不能被扫描到,否则会出错
    }

这样就多了两个ID可以为UID 或者 自定义的主键的inset方法啦

Sign in to comment

Status
Assignees
Milestones
Pull Requests
Successfully merging a pull request will close this issue.
Branches
Planed to start   -   Planed to end
-
Top level
Priority
参与者(3)
29 xiandafu 1578913709 4873597 soulmatelq 1578976162
Java
1
https://git.oschina.net/xiandafu/springboot-plus.git
git@git.oschina.net:xiandafu/springboot-plus.git
xiandafu
springboot-plus
springboot-plus

Search