MyBatis は削除操作を実装します

MyBatis は削除操作を実装します

1 を削除します

インターフェース

/**
 * 根据id删除
 */
void deleteById(int id);

SQLマッピング

<!--根据id删除-->
<delete id="deleteById">
    delete
    from tb_brand
    where id = #{id};
</delete>

テスト

削除前

画像-20220815200817474

  @Test
    public void testDeleteById() throws IOException {
    
    
//        设置参数
        int id = 6;

//    1.获取SQLSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//        2. 获取SqlSession对象
//        设置为自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
//        3. 获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//        4. 执行方法
        brandMapper.deleteById(id);
//        5. 释放资源
        sqlSession.close();
    }

削除後

画像-20220815200939965

2 一括削除

SQLの初期設定は次のとおりです。

<delete id="deleteByIds">
    delete
    from tb_brand
    where id in (?,?,?);
</delete>

これの問題は、動的に削除できないことです

クエスチョンマークはプレースホルダーですが、いくつ削除すればよいのかわからないので、プレースホルダーをいくつ入れればよいのかわかりません

解決:

タグを使用する

知らせ:

MyBatis は、配列パラメータを Map コレクションとしてカプセル化します。

  • デフォルト: 配列 = 配列
  • @Param アノテーションを使用して、マップ コレクションのデフォルト キーの名前を変更します。

今回は @Param アノテーションの使い方

インターフェース

/**
 * 批量删除
 */
void deleteByIds(@Param("ids") int[] ids);

SQLマッピング

<!--    批量删除-->
<delete id="deleteByIds">
    delete
    from tb_brand
    where id
    in (
    <foreach collection="ids" item="id" separator=",">
        #{id}
    </foreach>
    );
</delete>

テスト

7 8 9 を削除

画像-20220815202428287

 @Test
    public void testDeleteByIds() throws IOException {
    
    
//        设置参数
        int[] ids = {
    
    7, 8, 9};

//    1.获取SQLSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//        2. 获取SqlSession对象
//        设置为自动提交事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
//        3. 获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//        4. 执行方法
        brandMapper.deleteByIds(ids);
//        5. 释放资源
        sqlSession.close();
    }

画像-20220815202639936

最適化

SQLマッピング構成ファイルを最適化する

open 属性と close 属性を使用して、外側に手動で追加する括弧を省略します。括弧は MyBatis によって自動的に追加されます。

<delete id="deleteByIds">
    delete
    from tb_brand
    where id
    in
    <foreach collection="ids" item="id" separator="," open="(" close=")">
        #{id}
    </foreach>
    ;
</delete>

おすすめ

転載: blog.csdn.net/qq_45842943/article/details/126356894
おすすめ