Mybatis-plusにさらにプラスを追加する方法

ソース公開アカウント: Zhao Xiake

1. Mybatis-plusの基本機能

1.1 Mybatis-plus 組み込みメソッド

Mybatis-plusすぐに使用できるように、多くのホイールが構築されており、データベースの操作によく使用される 19 のメソッド ( など)BaseMapperがあります。Insert()deleteById()updateById()selectById()

UserMapper 開発時には、データベースを操作するためのこれらの共通メソッドを取得するために、継承を継承するだけでよく、BaseMapperこれらのメソッドを再度書き直す必要がなく、より便利です。

@Repository
public interface UserMapper extends BaseMapper<User> {
    
    

}

Mybatis-plus は、IServiceデータベースを操作するためのより豊富な方法を提供します。これを使用するときは、私たちのものUserServiceImpl を継承しServiceImplIService これらのメソッドを簡単に取得するためのインターフェイスを実装するだけで済みます。

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IService {
    
    


}

1.2 問題点

Mybatis-plusそれは私たちに多くの方法を提供しますが、私たちのニーズも制限します。たとえば、私には非常に一般的なニーズがいくつかあります。

  • データを論理的に削除する場合、操作者はデータベースに記録されます。Mybatis-plusこのメソッドを使用する場合removeById(1L)、このメソッドはデータベース論理ビットを削除済み状態に設定することしかできず、オペレーターはそれをデータベースに記録できません。

  • 各テーブルには tenant_id があり、 tenant_id からテーブル内の ID を調べたいのですが、方法Mybatis-plusがありませんselectIdByTenantId()その場合、テーブルごとに 1 つしか記述できずselectIdByTenantId、コードは確かに少し冗長になります。

    したがって、上記の既存の問題に対応して、  Mybatis-plusもう少しプラスを追加できます。

2. BaseMapper にいくつかのプラスを追加します。

2.1 BaseMapper にいくつかのメソッドを追加する

Mybatis-plus組み込みメソッドは継承されますAbstractMethod 


public class DeleteById extends AbstractMethod {
    
    

    public DeleteById() {
    
    
        super("deleteById");
    }
}

したがって、クラスを作成しDeleteAndUpdateById、そのUpdateById書き込みメソッドを模倣してエンティティ内のフィールドをデータベースに更新し、トゥームストーン ビットを削除済み状態に設定できます。

public class DeleteAndUpdateById extends AbstractMethod {
    
    


    /**
     * 注入自定义 MappedStatement
     * 根据id逻辑删除,顺带更新数据
     *
     * @param mapperClass mapper 接口
     * @param modelClass  mapper 泛型
     * @param tableInfo   数据库表反射信息
     * @return MappedStatement
     */
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
    
    
        String methodName = CustomSqlMethod.DELETE_AND_UPDATE_BY_ID.getMethod();
        String logicSql = CustomSqlMethod.DELETE_AND_UPDATE_BY_ID.getSql();
        final String additional = optlockVersion(tableInfo) + tableInfo.getLogicDeleteSql(true, true);
        logicSql = String.format(logicSql,
                tableInfo.getTableName(),
                sqlSet(false, false, tableInfo, false, ENTITY, ENTITY_DOT),
                tableInfo.getKeyColumn(),
                ENTITY_DOT + tableInfo.getKeyProperty(),
                additional);
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, logicSql, modelClass);
        return addUpdateMappedStatement(mapperClass, modelClass, methodName, sqlSource);
    }

    /**
     * SQL 更新 set 语句
     *
     * @param logic          是否逻辑删除注入器
     * @param ew             是否存在 UpdateWrapper 条件
     * @param table          表信息
     * @param judgeAliasNull
     * @param alias          别名
     * @param prefix         前缀
     * @return sql
     */
    @Override
    protected String sqlSet(boolean logic, boolean ew, TableInfo table, boolean judgeAliasNull, String alias, String prefix) {
    
    
        StringBuilder sqlScriptBuilder = new StringBuilder();
        // 添加删除的sql
        sqlScriptBuilder.append(table.getLogicDeleteSql(false, false))
                .append(DOT_NEWLINE);
        // 添加更新的sql
        sqlScriptBuilder.append(table.getAllSqlSet(true, prefix));
        String sqlScript = sqlScriptBuilder.toString();
        if (judgeAliasNull) {
    
    
            sqlScript = SqlScriptUtils.convertIf(sqlScript, String.format("%s != null", alias), true);
        }
        if (ew) {
    
    
            sqlScript += NEWLINE;
            sqlScript += convertIfEwParam(U_WRAPPER_SQL_SET, false);
        }
        sqlScript = SqlScriptUtils.convertSet(sqlScript);
        return sqlScript;
    }
}

DeleteAndUpdateById次に、メソッドを に追加する必要がありますDefaultSqlInjector

@Component
public class CustomSqlInjector extends DefaultSqlInjector {
    
    

    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
    
    
        List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
        methodList.add(new DeleteAndUpdateById());
        return methodList;
    }
}

1 つ作成しCustomBaseMapperて継承しBaseMapperdeleteAndUpdateByIdメソッドを追加します

public interface CustomBaseMapper<T> extends com.baomidou.mybatisplus.core.mapper.BaseMapper<T> {
    
    

    /**
     * 根据id做逻辑删除,并同时修改内容
     *
     * @param entity
     * @return
     */
    int deleteAndUpdateById(@Param(Constants.ENTITY) T entity);
}

最後にrにメソッドを持つようにUserMapper継承します。CustomBaseMapperUserMappedeleteAndUpdateById

@Repository
public interface UserMapper extends CustomBaseMapper<User> {
    
    

}

2.2 IServce にいくつかのメソッドを追加する

ICustomServiceメソッドの継承を定義する IService

public interface ICustomService<T> extends IService<T> {
    
    
    List<Long> selectByTenantIds(List<Long> tenantIds);
    int deleteAndUpdateById(@Param(Constants.ENTITY) T entity);
}

次に、CustomBaseServiceImpl実装ICustomServiceでメソッドを作成します

public class CustomBaseServiceImpl<M extends CustomBaseMapper<T>, T extends BaseDomain> extends ServiceImpl<M, T> {
    
    
    /**
     * 删除并更新内容 根据ID
     *
     * @param entity 对象
     * @return
     */
    public int deleteAndUpdateById(T entity) {
    
    
        return baseMapper.deleteAndUpdateById(entity);
    }


    public List<Long> selectByTenantIds(List<Long> tenantIds) {
    
    
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        queryWrapper.in(!tenantIds.contains(0L), "tenant_id", tenantIds);
        return listObjs(queryWrapper, id -> Long.valueOf(id.toString()));
    }
}      

最後に、UserService独自の を継承するように変更しますICustomServiceUserServiceImpl

public interface ICustomService<T> extends IService<T> {
    
    
    List<Long> selectByTenantIds(List<Long> tenantIds);
    int deleteAndUpdateById(@Param(Constants.ENTITY) T entity);
}

3. テスト

3.1 試験方法

上記の変換により、すべてのサービスにdeleteAndUpdateById()メソッドとselectByTenantIds()メソッドが追加されます。

class ApplicationTests {
    
    

    @Resource
    private UserService userService;

    @Test
    void testDeleteAndUpadteById() {
    
    
        User user = userService.getById(1L);
        user.setModifiedBy("赵侠客");
        user.setModifiedAt(LocalDateTime.now());
        userService.deleteAndUpdateById(user);
        User dbUser = userService.getById(1L);
        Assert.isTrue(dbUser == null, "删除成功");
    }

    @Test
    void test() {
    
    
        var userIds = userService.selectByTenantIds(List.of(1L));
        log.info("userIds:{}", userIds);
        Assert.isTrue(userIds != null);
    }
}

4. まとめ

ここでは 2 つのプラス機能を追加しただけです。独自のニーズに応じて、さらにMybatis-plus多くの機能を追加できます。拡張できる主なプラス ポイントは次のとおりです。CustomBaseMapperICustomService

  • 実際のニーズを満たすことができない Mybatis-plus の組み込みメソッドを書き直す
  • コード内の多くの一般的なメソッドを Plus パブリック関数に抽出できます。

ソースコードアドレス: https://gitee.com/whzhaochao/mybatis-plus-plus

元のアドレス: https://mp.weixin.qq.com/s/JnS9pmZvlvTvnutnpdYAwA

おすすめ

転載: blog.csdn.net/whzhaochao/article/details/132778212