mybatis學習筆記05-註解

mybatis註解開發


  1. 方法上的註解
    1. 原來xml中的<select>, <update>, <insert>和<delete>分別對應註解
      • @select("sql語句")
      • @update("sql語句")
      • @insert("sql語句")
      • @delete("sql語句")
    2. 結果映射配置: 原來xml中的<resultMap>對應 @resultssql

      @Select("select * from t_account where id = #{id}")
      @Results(id = "accountMap", value = {
              @Result(id = true, column = "id", property = "id"),
              @Result(column = "user_id", property = "user",
                      one = @One(
                              select = "cn.ann.mapper.UserMapper.getUserById", fetchType = FetchType.EAGER
                      ))
      })
      Account getAccountById(Integer id);
      • <resultMap>中的<id>對應@Result(id = true, column = "id", property = "id")
      • <resultMap>中的<result>對應@Result註解去掉id屬性, 或是將id屬性設爲false
      • <resultMap>中的<association>對應@Result註解中的 one = @one(...), 其中, property指定屬性, column指定做爲參數傳入方法的列
      @Select("select * from t_user where id = #{id}")
      @Results(id = "userMap", value = {
              @Result(id = true, property = "id", column = "id"),
              @Result(property = "accounts", column = "id",
                      many = @Many(select = "cn.ann.mapper.AccountMapper.getAccountsByUserId",
                              fetchType = FetchType.LAZY))
      })
      User getUserById(Integer id);
      • <resultMap>中的<collection>對應@Result註解中的 many = @many(...), 其中, property指定屬性, column指定做爲參數傳入方法的列
        @ResultMap("accountMap")
      • @ResultMap至關於<select>中的resultMap屬性, 它須要一個已經存在的結果映射集的 id 值
  2. 接口上的註解
    1. @Mapper
      • 我並不清楚這個註解具體有什麼做用, 多是標明這個接口是一個mapper類
    2. @CacheNamespace
      • 配置是否開啓緩存
    3. @CacheNamespaceRef
      • 引用其餘命名空間的緩存
相關文章
相關標籤/搜索