13、MyBatisアノテーションの開発

Mybatisノート:

意味:元々xmlに配置されていた構成情報とSQLステートメントをプログラムに入れて記述します。実現関数は同じです。

利点:より優れた開発エクスペリエンスが提供されるため、プログラム開発をより迅速に使用できます
ここに画像の説明を挿入

1つ、クエリ

  1. 注釈インターフェースを作成する
 public interface GoodsDAO {
    
     
   // 传入的sql和之前在xml文件里配置的一致即可  
     @Select("select * from t_goods where current_price between #{min} and #{max} order by current_price #{limt}")  
   // 因为不能自动判断上面的参数和下面哪个参数相对应,所以需要手动配置    
   public List<Goods> selectByPriceRange(@Param("min") float max, @Param("max") 
   float min,@Param("limt") float limt);}
  1. mybatis-config.xmlファイルに対応する手順を追加しました
   <!--两种配置方式,二选一即可。-->
    <!--推荐使用第二种,因为随着工程越来越大,配置信息也越来越多,不便维护。
    如果使用包的话,就只用写这一行,mybatis加载时候会对整个包进行扫描,极大简化了配置-->
<mappers>
    <!--<mapper class="com.imooc.mybatis.dao.GoodsDAO"/>-->
    <package name="com.imooc.mybatis.dao"/>
</mappers>
  1. テスト
@Test
public void testSelectByPriceRange() throws Exception {
    
    
    SqlSession sqlSession = null;
    try {
    
    
        sqlSession = MyBatisUtils.openSession();
        // goodsDAO虽然是接口,但是运行的时候session会根据其配置信息动态生成其实现类
        GoodsDAO goodsDAO = sqlSession.getMapper(GoodsDAO.class);
        // 进行查询
        List<Goods> goods = goodsDAO.selectByPriceRange(20f, 10f, 20);
        System.out.println(goods.size());
    } catch (Exception e) {
    
    
        throw e;
    } finally {
    
    
        MyBatisUtils.closeSession(sqlSession);
    }
}

2、追加

  1. 注釈インターフェースを作成する
   // 插入
    @Insert("insert into t_goods(title, sub_title, original_cost, current_price, discount, is_free_delivery, category_id)" +
            "values(#{title},#{subTitle},#{originalCost},#{currentPrice},#{discount},#{isFreeDelivery},#{categoryId})")
    @SelectKey(statement = "select last_insert_id()",before = false, resultType = Integer.class,keyProperty = "goodsId")
    public int insert(Goods goods);
  1. mybatis-config.xmlファイルに対応する手順を追加しました
 <!--两种配置方式,二选一即可。-->
    <!--推荐使用第二种,因为随着工程越来越大,配置信息也越来越多,不便维护。
    如果使用包的话,就只用写这一行,mybatis加载时候会对整个包进行扫描,极大简化了配置-->
<mappers>
    <!--<mapper class="com.imooc.mybatis.dao.GoodsDAO"/>-->
    <package name="com.imooc.mybatis.dao"/>
</mappers>
  1. テスト
@Test
    public void testInsert() throws Exception {
    
    
        SqlSession sqlSession = null;
        try {
    
    
            sqlSession = MyBatisUtils.openSession();
            Goods goods = new Goods();
            goods.setTitle("t1");
            goods.setSubTitle("t2");
            goods.setCategoryId(12);
            goods.setCurrentPrice(200f);
            goods.setDiscount(20f);
            goods.setIsFreeDelivery(1);
            goods.setOriginalCost(201f);
            GoodsDAO goodsDAO = sqlSession.getMapper(GoodsDAO.class);
            goodsDAO.insert(goods);
            sqlSession.commit();
        } catch (Exception e) {
    
    
            if (sqlSession != null) {
    
    
                sqlSession.rollback();
            }
            throw e;
        } finally {
    
    
            MyBatisUtils.closeSession(sqlSession);
        }
    }

3つ目は、結果のマッピングを実現する

  1. 注釈インターフェースを作成する
    @Select("select * from t_goods")
    // 相当于xml的resultMap
    @Results(
          {
    
    
              // 相当于<id> ,里面的id字段表示是否是主键id
              // dto里有什么参数,这里就传入什么
              @Result(column = "goods_id", property = "goodsId", id = true),
              @Result(column = "title", property = "title"),
              @Result(column = "current_price", property = "currentPrice")
          }
    )
    public List<GoodsDTO> selectAll();
}

  1. mybatis-config.xmlファイルに対応する手順を追加しました
 <!--两种配置方式,二选一即可。-->
    <!--推荐使用第二种,因为随着工程越来越大,配置信息也越来越多,不便维护。
    如果使用包的话,就只用写这一行,mybatis加载时候会对整个包进行扫描,极大简化了配置-->
<mappers>
    <!--<mapper class="com.imooc.mybatis.dao.GoodsDAO"/>-->
    <package name="com.imooc.mybatis.dao"/>
</mappers>
  1. テスト
 @Test
    public void testSelectAll() throws Exception {
    
    
        SqlSession sqlSession = null;
        try {
    
    
            sqlSession = MyBatisUtils.openSession();
            GoodsDAO goodsDAO = sqlSession.getMapper(GoodsDAO.class);
            List<GoodsDTO> list = goodsDAO.selectAll();
            System.out.println(list.size());
            sqlSession.commit();
        } catch (Exception e) {
    
    
            if (sqlSession != null) {
    
    
                sqlSession.rollback();
            }
            throw e;
        } finally {
    
    
            MyBatisUtils.closeSession(sqlSession);
        }
    }

総括する:

  1. XMLは保守性が高く、SQLはxmlで柔軟に変更できます。コードを直接調整するだけで、アノテーションを使用してプログラミングエクスペリエンスを向上させることができます。
  2. XMLプロジェクトは大規模なチーム協力プロジェクトに適しており、アノテーションは小規模なアジャイル開発に適しています。

おすすめ

転載: blog.csdn.net/qq_36792120/article/details/112549719