参考:https://gitee.com/baomidou/mybatis-plus-samples/tree/master/mybatis-plus-sample-deluxe

    定义Mapper

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

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

    1. public class InsertIgnore extends AbstractMethod {
    2. @Override
    3. public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
    4. String sql = "insert ignore into %s %s values %s";
    5. StringBuilder fieldSql = new StringBuilder();
    6. fieldSql.append(tableInfo.getKeyColumn()).append(",");
    7. StringBuilder valueSql = new StringBuilder();
    8. valueSql.append("#{").append(tableInfo.getKeyProperty()).append("},");
    9. tableInfo.getFieldList().forEach(x -> {
    10. fieldSql.append(x.getColumn()).append(",");
    11. valueSql.append("#{").append(x.getProperty()).append("},");
    12. });
    13. fieldSql.delete(fieldSql.length() - 1, fieldSql.length());
    14. fieldSql.insert(0, "(");
    15. fieldSql.append(")");
    16. valueSql.insert(0, "(");
    17. valueSql.delete(valueSql.length() - 1, valueSql.length());
    18. valueSql.append(")");
    19. SqlSource sqlSource = languageDriver.createSqlSource(configuration, String.format(sql, tableInfo.getTableName(), fieldSql.toString(), valueSql.toString()), modelClass);
    20. return this.addInsertMappedStatement(mapperClass, modelClass, "insertIgnore", sqlSource, new NoKeyGenerator(), null, null);
    21. }
    22. }

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

    1. public class CommonSqlInjector extends DefaultSqlInjector {
    2. @Override
    3. public List<AbstractMethod> getMethodList() {
    4. List<AbstractMethod> methodList = super.getMethodList();
    5. //
    6. methodList.add(new InsertIgnore());
    7. return methodList;
    8. }
    9. }

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

    1. @Configuration
    2. public class MyBatisPlusConfig {
    3. @Bean
    4. public CommonSqlInjector commonSqlInjector() {
    5. return new CommonSqlInjector();
    6. }
    7. }

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