Mybatis Plus自定义Mapper方法实现

1,457 阅读1分钟

参考:gitee.com/baomidou/my…

定义Mapper

public class CommonMapper<T> extends BaseMapper<T> {
    int insertIgnore(T t);
}

使用AbstractMethod定义CommonMapper中insertIgnore方法的实现:

public class InsertIgnore extends AbstractMethod {
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql = "insert ignore into %s %s values %s";
        StringBuilder fieldSql = new StringBuilder();
        fieldSql.append(tableInfo.getKeyColumn()).append(",");
        StringBuilder valueSql = new StringBuilder();
        valueSql.append("#{").append(tableInfo.getKeyProperty()).append("},");
        tableInfo.getFieldList().forEach(x -> {
            fieldSql.append(x.getColumn()).append(",");
            valueSql.append("#{").append(x.getProperty()).append("},");
        });
        fieldSql.delete(fieldSql.length() - 1, fieldSql.length());
        fieldSql.insert(0, "(");
        fieldSql.append(")");
        valueSql.insert(0, "(");
        valueSql.delete(valueSql.length() - 1, valueSql.length());
        valueSql.append(")");
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, String.format(sql, tableInfo.getTableName(), fieldSql.toString(), valueSql.toString()), modelClass);
        return this.addInsertMappedStatement(mapperClass, modelClass, "insertIgnore", sqlSource, new NoKeyGenerator(), null, null);
    }
}

定义sql注入器,将定义的InsertIgnore方法的实现添加到注入器中的方法列表中

public class CommonSqlInjector extends DefaultSqlInjector {
    @Override
    public List<AbstractMethod> getMethodList() {
        List<AbstractMethod> methodList = super.getMethodList();
        // 
        methodList.add(new InsertIgnore());
        return methodList;
    }
}

配置注入器,使得注入器生效

@Configuration
public class MyBatisPlusConfig {
    @Bean
    public CommonSqlInjector commonSqlInjector() {
        return new CommonSqlInjector();
    }
}

此时,CommonMapper方法可以正常使用了, 可以在需要实现insertIgore时可以用CommonMapper替换BaseMapper